Dagger 2 – two provides method that provide same interface

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

Leave a Comment