Dagger 2 - two provides method that provide same interface

后端 未结 4 1268
慢半拍i
慢半拍i 2020-12-24 05:33

lets say I have:

public interface Shape  {}


public class Rectangle implements Shape {

}

public class Circle implements Shape {

}

and I

4条回答
  •  攒了一身酷
    2020-12-24 06:09

    I recently post the answer to a question like this in this post :

    Dagger 2 : error while getting a multiple instances of same object with @Named

    You need to use @Named("someName")in your module like this:

    @Module
    public class ApplicationModule {
    private Shape rec;
    private Shape circle;
    
    public ApplicationModule() {
        rec = new Rectangle();
        circle= new Circle ();
    }
    
    @Provides
     @Named("rect")
    public Shape provideRectangle() {
        return rec ;
    }
    
    @Provides
     @Named("circle")
    public Shape provideCircle() {
        return circle;
    }
    

    }

    Then wherever you need to inject them just write

    @Inject
    @Named("rect")
     Shape objRect;
    

    its funny but you have to inject in a different way in Kotlin:

    @field:[Inject Named("rect")]
    lateinit var objRect: Shape
    

提交回复
热议问题