匕首 2 安卓版来救援。它提供了以下概念:AndroidInjector
,这是一个Component
可以用于以静态方式注入实例,而无需知道依赖项提供程序。此外,使用Dagger-
开箱即用提供前缀类,注入的依赖项看起来像是来自无处。惊人的。
您所要做的就是在库中声明一个顶级Module
它安装在应用程序中Component
. This Module
将提供所有依赖项和SubComponent
库需要的s,会自动继承@AppContext Context
您在依赖关系图中播种的内容,准备好注入库中的任何位置,以及您通过主应用程序提供的每个依赖关系Component
.
这是一个简短的示例(用 Kotlin 编写):
@Component(modules = [
AndroidSupportInjectionModule::class,
AppModule::class,
LibraryModule::class //plug-in the library to the dependency graph
])
@Singleton
interface AppComponent : AndroidInjector<App> {
@Component.Builder
abstract class Builder : AndroidInjector.Builder<App>() {
@BindsInstance
abstract fun appContext(@AppContext context: Context)
override fun seedInstance(instance: App) {
appContext(instance)
}
}
}
编辑:扩展示例
应用程序子类的示例:
// DaggerApplication provides out-of-the-box support to all the AndroidInjectors.
// See the class' code to understand the magic.
public class App extends DaggerApplication {
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
// We only provide its own Injector, the Application Injector,
// that is the previous AppComponent
return DaggerAppComponent.builder().create(this);
}
在你的 Android 库中:
@Module
public abstract class LibraryModule {
@ContributesAndroidInjector
public abstract LibraryActivity contributeLibraryActivityInjector();
}
public class LibraryActivity extends DaggerAppCompatActivity {
@Inject
@AppContext
Context appContext;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceSate);
// here you automagically have your injected application context!
ExternalSingleton.getInstance(appContext)
}
}