我写了一篇关于这方面的文章,其中有很多细节:Dagger2 for Modular Architecture,但下面简短的回答。
你必须以不同的方式使用Dagger2。您无需为每个功能模块使用模块或子组件,而需要使用具有对基本AppComponent的依赖关系的组件。
在一个模块中,我们通常是这样做:
@Singleton
@Component(modules = arrayOf(NetworkModule::class, RepositoryModule::class,
SubcomponentModule::class))
interface ApplicationComponent : AndroidInjector<MyApplication> {
val userRepository: UserRepository
val apiService: ApiService
}
@Module
object NetworkModule {
@Provides
@Singleton
@JvmStatic
fun provideApiService(okHttp: OkHttp): ApiService {
return ApiSerive(okHttp)
}
}
但正如你说你没有访问SubComponentModule这可能是在其他功能模块的另一个模块或引用匕首模块。
您只需创建一个功能模块中根据ApplicationComponent这样一个新的匕首模块:
@Browser
@Component(modules = [(BrowserModule::class)],
dependencies = [(AppComponent::class)])
interface BrowserComponent : AndroidInjector<AppCompatActivity> {
@Component.Builder
abstract class Builder: AndroidInjector.Builder<AppCompatActivity>(){
/**
* explicity declare to Dagger2
* that this builder will accept an AppComponent instance
**/
abstract fun plus(component: AppComponent): Builder
}
}
以及相应的功能活动将构建组件:
class BrowserActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DaggerBrowserComponent
.builder()
/**
* we have to provide an instance of the AppComponent or
* any other dependency for this component
**/
.plus((application as MyApplication).component)
.build()
.inject(this)
}
}
从这[InstantApps兼容图书馆](https://developer.android.com/topic/instant-apps/prepare.html#identify_tested_compatible_libraries)链接,也许匕首不仅仅支持... –
该链接仅适用于Google图书馆,不适用于第三方-派对。 – TWL
你可以检查这个网址https://github.com/ragdroid/instant-app-dagger它可以帮助你。 –