简体   繁体   中英

What is the best way to inject a class of a child type with Dagger 2?

Is it just to provide the child type in the module ? or is there a more direct way eg by using constructor injection with some parameter ?

@Module
class TestModule() {

  @Provides
  @Singleton
  fun provideDummy(): Dummy = DummyChild()

}

class MainActivity : AppCompatActivity() {
    @Inject
    lateinit var dummy: Dumy

    override fun onCreate(savedInstanceState: Bundle?) {
       ...
    }

    ...
}

That's how it needs to be done. The Module provides components that can be injected.

In the above case TestModule is the module which can provide DummyChild . It becomes a complicated if the constructor of DummyChild required a parameter. In that case the parameter needs to be injected as well.

@Module
class TestModule() {

@Provides
@Singleton
fun provideDummy(Context context): Dummy = DummyChild(context)
}

In the above case, context needs to be provided as well. You should have an exposed Provides method that can provide Context.

or is there a more direct way eg by using constructor injection with some parameter ?

Absolutely!

@Module
class TestModule() {

  @Provides
  @Singleton
  fun provideDummy(): Dummy = DummyChild() // bad, we construct it ourselves!

}

You should let Dagger care about where the object comes from, so calling the constructor is usually not a good idea (unless this is really what you want). The proper way to bind an implementation is by using a @Provides method and requesting the child, directly returning it, or just using the @Binds annotation which will do effectively the same, but possibly more optimized than @Provides .

@Module
class TestModule() {

  @Provides
  fun provideDummy(implementation : DummyChild): Dummy = implementation // better!

  // or with @Binds

  @Binds
  abstract fun provideDummy(implementation : DummyChild): Dummy // also good

}

@Singleton class DummyChild @Inject constructor()

Notice that I removed the @Singleton from the methods, as this is usually an implementation detail of DummyChild , rather than the interface, but you can of course still add it to the method if you wish to do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM