As far as I have understood dagger, there are two ways for Dagger to know how to create an object:
- scanning for annotations at constructors
- scanning modules for provider methods
With injection, the situation is not that easy. If you combine creation and injection, then everything is fine:
- scanning for annotations at fields or methods
- scanning modules for method parameters of provider methods
When I only want to use injection, because the object got already created by some other party, things are different. In this case Dagger only supports this:
- scanning for annotations at fields or methods to create a MembersInjector that can be used at component level with an inject method.
- not supported: providing an implementation of a MembersInjector in a module
What I would like to do is something like this:
// imported from some library. instances get created but not initialized by the library
final class Type {
A a;
B b;
private Type() {}
public void initialize(A a, B b) {this.a=a; this.b=b};
}
My component and modules can provide A and B.
What I am looking for is something like
@Component(modules = MyModule.class)
interface MyComponent {
Type inject(Type t);
}
and a way to provide my own implementation of the MembersInjector. Like this:
@Module
class MyModule {
@Injects
MembersInjector<Type> provideTypeInjector(A a, B b) {
return instance -> {
instance.initialize(a, b);
}
}
}
Dagger can then generate the necessary code for DaggerMyComponent.
I know I can write something myself. A pattern might be:
interface MyInjector<T> {
T inject(T);
}
@Module
class MyModule {
@Provides
MyInjector<Type> provideTypeInjector(A a, B b) {
return instance -> {
instance.initialize(a, b);
}
}
}
@Component(modules = MyModule.class)
interface MyComponent {
MyInjector<Type> getTypeInjector();
}
Initializing the object can then be achieved by doing:
component.getTypeInjector().inject(typeInstance);
but I think
component.inject(typeInstance);
would be much nicer and more idiomatic.
What do you think?
As far as I have understood dagger, there are two ways for Dagger to know how to create an object:
With injection, the situation is not that easy. If you combine creation and injection, then everything is fine:
When I only want to use injection, because the object got already created by some other party, things are different. In this case Dagger only supports this:
What I would like to do is something like this:
My component and modules can provide
AandB.What I am looking for is something like
and a way to provide my own implementation of the
MembersInjector. Like this:Dagger can then generate the necessary code for
DaggerMyComponent.I know I can write something myself. A pattern might be:
Initializing the object can then be achieved by doing:
but I think
would be much nicer and more idiomatic.
What do you think?