Sobes.tech
Middle+

What is multi-binding in Dagger?

sobes.tech AI

Answer from AI

Multibinding in Dagger allows declaring a set of objects (for example, Set or Map) from different modules, which will be assembled into a collection during injection. This is useful when you have multiple implementations of the same interface or type that need to be handled uniformly.

There are two main types of multibinding:

  1. Set Multibinding: Creates a Set from the provided objects.

    • Annotation @IntoSet.
    @Module
    abstract class MyModule {
        @Binds @IntoSet
        abstract MyInterface provideImpl1(Impl1 impl);
    
        @Binds @IntoSet
        abstract MyInterface provideImpl2(Impl2 impl);
    }
    
    // At injection point
    @Inject
    Set<MyInterface> myImplementations;
    
  2. Map Multibinding: Creates a Map with keys and values.

    • Annotation @IntoMap.
    • You need to provide an annotation for the key (for example, @StringKey, @IntKey, @EnumKey).
    @Module
    class MyModule {
        @Provides @IntoMap
        @StringKey("key1")
        MyValueType provideValue1() {
            return new MyValueType("value1");
        }
    
        @Provides @IntoMap
        @StringKey("key2")
        MyValueType provideValue2() {
            return new MyValueType("value2");
        }
    }
    
    // At injection point
    @Inject
    Map<String, MyValueType> myMap;
    

Multibindings simplify adding new elements to a collection without changing the code where this collection is used.