Ofek Agmon
Ofek Agmon

Reputation: 5198

Dagger 2 - two provides method that provide same interface

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?

Upvotes: 46

Views: 31017

Answers (4)

Amir Ziarati
Amir Ziarati

Reputation: 15107

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

Upvotes: 67

Albert Vila Calvo
Albert Vila Calvo

Reputation: 15865

In addition to @Named and custom qualifiers (shown in other responses), you can also use a custom qualifier with an enum parameter:

// Definition

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ShapeType {
  ShapeTypeEnum value(); /* default ShapeTypeEnum.RECTANGLE; */
}

public enum ShapeTypeEnum {
  RECTANGLE, CIRCLE
}

// Usage

@Provides @ShapeType(ShapeTypeEnum.RECTANGLE)
public Shape provideRectangle() {
    return new Rectangle();
}

@Inject @ShapeType(ShapeTypeEnum.RECTANGLE) Shape rectangle;

This is an hybrid between @Named (which requires String keys, which is error-prone and can't be auto-completed) and custom qualifiers (which requires a file for each implementation).

Upvotes: 4

Bryan
Bryan

Reputation: 15166

I do not think it is a good idea to use the new operator within the constructor of the Module. This would create an instance of each of your provided objects upon initialization of your object graph (i.e. when you call new ApplicationModule()) instead of when Dagger needs the object for the first time. In this case (with only two objects), it would be negligible, but in larger projects this could cause a bottleneck upon the start of the application. Instead, I would follow the suggestion by @sector11, and instantiate your objects in the @Provides annotated methods.

As for providing two objects of the same type, both @Jeff and @Amir are correct. You can either use the provided @Named() qualifier, or create your own qualifiers, like so:

@Qualifier @Retention(RetentionPolicy.RUNTIME)
public @interface RectangleShape {}

@Qualifier @Retention(RetentionPolicy.RUNTIME)
public @interface CircleShape {}

Then your ApplicationModule should look like this:

@Module
public class ApplicationModule {

    @Provides @RectangleShape // @Named("rectangle")
    public Shape provideRectangle() {
        return new Rectangle();
    }

    @Provides @CircleShape // @Named("circle")
    public Shape provideCircle() {
        return new Circle();
    }

}

With this you can inject these objects into your classes like this:

@Inject @RectangleShape /* @Named("rectangle") */ public Shape mRectangle;
@Inject @CircleShape /* @Named("circle") */ public Shape mCircle;

If you need to provide the instances of your Shape classes without an @Inject annotation, you can do so in your Component class:

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

    void inject(MyApplication application);

    @RectangleShape // @Named("rectangle")
    Shape getRectangle();

    @CircleShape // @Named("circle")
    Shape getCircle();

}

These methods will provide the same instance of each class provided by the @Provides annotated methods.

Upvotes: 10

Jeff Bowman
Jeff Bowman

Reputation: 95774

@Qualifier annotations are the right way to distinguish different instances or injection requests that have the same type. The main User's Guide page has a whole section on them.

@Qualifier @Retention(RUNTIME)
public interface Parallelogram {} /* name is up to you */

// In your Module:
@Provides @Parallelogram
public Shape provideRectangle() {
    return rec ;
}

// In your other injected types:
@Inject @Parallelogram Shape parallelogramShape;
// or
@Inject @Parallelogram Provider<Shape> parallelogramShapeProvider;

// In your Component:
@Parallelogram Shape provideRectangle();

Aside: Though I agree with sector11 that you shouldn't use new in injected types, Modules are exactly the correct place to call new if needed. Aside from adding the qualifier annotations, I'd say your Module looks just right to me.


EDIT regarding the use of @Named compared to custom qualifier annotations:

  • @Named is a built-in @Qualifier annotation, much like the one I've created above. For simple cases, it works great, but because the binding is just a string you won't get as much help from your IDE in detecting valid keys or autocompleting the key.
  • Like with Named's string parameter, custom qualifiers can have string, primitive, enum, or class literal properties. For enums, IDEs can often autocomplete valid values.
  • @Named and custom qualifiers can be accessed from annotations in exactly the same way by specifying the annotation on the component method, as I've done with @Parallelogram above.

Upvotes: 17

Related Questions