Dagger 2:使我的Foo类可以在Kotlin的其他类中注射

问题描述 投票:0回答:2

我正在用Kotlin和Dagger 2开发一个Android项目。我有一个MyModule,其中定义了一些提供程序功能。

@Module
object MyModule {
   @Provides
   @JvmStatic 
   internal fun provideSomething(): Something {
      ...
   }
}

在我的Foo类中,我将Something作为成员变量注入:

class Foo(@Inject val something: Something) {
}

但是现在我想让这个Foo类也可以注入到另一个类中,例如在名为Bar的类中:

class Bar(@Inject val foo: Foo)

如何实现?如果使用Java,我可以做:

class Foo {
  // I inject something
  @Inject
  private Something something;

  // I also make Foo to be injectable to other class
  @Inject
  public Foo()
}

但是如何在我的Kotlin Foo类中实现相同?

android kotlin dagger-2
2个回答
0
投票

在Kotlin中,您必须这样做:

class Foo @Inject constructor(val something: Something) {
}

我不确定是否也可以使用相同的名称。


0
投票

假设Something是您创建的类。您甚至不需要提供@Module

您可以这样做,

class Something @Inject constructor() {

}

您只需将@Inject添加到Something构造函数中,就是这样,Dagger知道如何提供它。然后在您的Foo类中>

class Foo @Inject constructor() {

  @Inject
  lateinit var something: Something

}

完成,如果您拥有Something类,则不需要@Module和@Component。

但是

如果类Something不在您的控制之下,那么我们需要走很长的路,例如,

步骤1:创建模块

@Module
object MyModule {
   @Provides
   @JvmStatic 
   internal fun provideSomething(): Something {
      ...
   }
}

第2步:定义组件

@Component(modules = [MyModule::class])
interface MyComponent {
    fun inject(foo: Foo) //mention the place where you need to inject variables
}

第3步:启动组件

    class Foo @Inject constructor(){

          @Inject
          lateinit var something:Something

            init{
               DaggerMyComponent().create().inject(this) //do this before using `something` or else face `UninitializedPropertyException`

             //You can now freely use `something`, **Dagger** has already performed his magic
            }


        }

更新:

假设Something具有参数化的构造函数,看起来像这样,class Something @Inject constructor(mRandom : RandomClass),再次出现两种可能性

如果您拥有RandomClass,您可以像这样将[InC]构造函数添加@Inject,

RandomClass

就是这样,Dagger

将在需要的地方提供class RandomClass @Inject constructor(){ }

并且如果RandomClass不在您的控制之下,则需要使用这样的RandomClass来提供它,

@Module

将此@Module object RandomModule { @JvmStatic @Provides fun providesRandomClass(): RandomClass { ... } } 添加到您的@Module并在需要依赖项的任何地方启动@Component示例已在上面的步骤中提供]]。

故事的寓意是,一种或另一种匕首应该知道如何提供 @Component

对于您的特定示例,假设我们有

RandomClass

只需告诉匕首

如何提供class Something @Inject constructor(mString:String,customType:CustomType){ } String
CustomType

然后是对@Module object CustomModule { @JvmStatic @Provides @Named("AnyName") //Just to differentiate which string we need fun providesString() = "AnyName" @JvmStatic @Provides fun providesCustomType(): CustomType { ... } } 构造函数的最后一点修改,

Something
© www.soinside.com 2019 - 2024. All rights reserved.