Dagger2 - How to use @Named with @BindsInstance

六眼飞鱼酱① 提交于 2020-07-21 07:30:28

问题


How is @Named used with @BindsInstance? I have the this component

interface AppComponent : AndroidInjector<MyApplication>{
    @Component.Builder
    abstract class Builder : AndroidInjector.Builder<MyApplication>() {

        @BindsInstance
        abstract fun preferenceName( @Named("PreferenceName") name : String ) : Builder
    }
}

and trying to inject in MyApplication

@Inject
@Named("PreferenceName")
lateinit var prefName : String

But it fails with MissingBinding for String. I could resolve this with a module provider but trying to avoid provider for constants.


回答1:


Update: Dagger 2.25.2 has eliminated the need for workaround:

  1. Kotlin support

    ii. Qualifier annotations on fields can now be understood without The need for @field:MyQualifier (646e033)

    iii. @Module object classes no longer need @JvmStatic on the provides methods. (0da2180)


This doesn't have anything to do with @BindsInstance, but rather the @Named annotations on fields. You can tell from the "MissingBinding for String", which would otherwise give you an error about a Named string.

As in Svetlozar Kostadinov's article Correct usage of Dagger 2 @Named annotation in Kotlin, you'll need to clarify to Kotlin that you'd like the annotations to apply to the field.

@field:[Inject Named("PreferenceName")]
lateinit var prefName : String;

As Svetlozar puts it:

The reason is because in Kotlin annotations need to be slightly more complicated in order to work as expected from Java perspective. That’s coming from the fact that one Kotlin element may be a facade of multiple Java elements emitted in the bytecode. For example a Kotlin property is a facade of an underlying Java member variable, a getter and a setter. You annotate the property but what Dagger expects to be annotated is the underlying field.

Related: Dagger 2 constructor injection in kotlin with Named arguments



来源:https://stackoverflow.com/questions/54115182/dagger2-how-to-use-named-with-bindsinstance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!