How do I tell Dagger 2 which implementation to instantiate based on X?

后端 未结 3 664
既然无缘
既然无缘 2021-01-18 04:31

Inside a module, if I need to provide a different implementation of an interface based on a variable known at module construction time I can put the logic inside the @Provid

3条回答
  •  太阳男子
    2021-01-18 05:27

    Rather than Lazy, do option 1 with Provider. Lazy is just a Provider that memoizes locally (with the necessary double-checked locking), but because you know you'll only call one Provider exactly once, you can just inject the Provider instead and skip the synchronization overhead.

    @Provides
    FooInterface provideFooImplementation(
            Provider impl1,
            Provider impl2,
            ...,
            Provider impl10) {
        switch(state) {
            case STATE_1:
                return impl1.get();
            case STATE_2:
                return impl2.get();
            ...
            case STATE_10:
                return impl10.get();
        }
    }
    

    Option 2 will work, but you'll effectively skip the dependency wiring that Dagger could easily do for you, and Option 3 won't work as stated because your @Component annotation needs your list of modules to be a compile-time constant for your Dagger code generation to work.

    (A variant of Option 3 could work if your binding were to a constant or a zero-dependency class of one form or another, because then you could pass in an arbitrary subclass of your Module into your Component builder. However, Dagger can only analyze the bindings in the superclass module, and you'd have trouble if your @Provides method implementations take different parameters as yours would, so the switch is the best and clearest alternative I can think of.)

提交回复
热议问题