Dagger 2 - two provides method that provide same interface

Ofek Agmon picture Ofek Agmon · Oct 10, 2016 · Viewed 19.6k times · Source

lets say I have:

public interface Shape  {}


public class Rectangle implements Shape {

}

public class Circle implements Shape {

}

and I have a ApplicationModule which needs to provides instances for both Rec and Circle:

@Module
public class ApplicationModule {
    private Shape rec;
    private Shape circle;

    public ApplicationModule() {
        rec = new Rectangle();
        circle= new Circle ();
    }

    @Provides
    public Shape provideRectangle() {
        return rec ;
    }

    @Provides
    public Shape provideCircle() {
        return circle;
    }
}

and ApplicationComponent:

@Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
    Shape provideRectangle();
}

with the code the way it is - it won't compile. error saying

Error:(33, 20) error: Shape is bound multiple times.

It makes sense to me that this can't be done, because the component is trying to find a Shape instance, and it finds two of them, so it doesn't know which one to return.

My question is - how can I handle this issue?

Answer

Amir Ziarati picture Amir Ziarati · Oct 10, 2016

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