I'm trying to implement a factory with Dagger2 but I don't know how?
In a simplified example:
public class Foo{
public interface Factory{
Foo createNew();
}
private Bar bar;
public Foo(Bar bar){
this.bar= bar;
}
}
I'd like to set a method that provides Foo.Factory instances
@Module
public class TestModule{
@Provides
Bar provideBar(){
return new Bar();
}
@Provides
Foo.Factory provideFooFactory(){
// ??????
}
}
The result should be something like (getting the Bar instance from the module of course):
new Foo.Factory(){
@Override
public Foo createNew() {
return new Foo(new Bar());
}
};
What is the correct approach to achieve this?
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
A factory is a type with a single method that returns a new component instance each time it is called. The parameters of that method allow the caller to provide the modules, dependencies and bound instances required by the component.
Dagger automatically generates code that mimics the code you would otherwise have hand-written. Because the code is generated at compile time, it's traceable and more performant than other reflection-based solutions such as Guice. Note: Use Hilt for dependency injection on Android.
I have a working solution. Let me know if you have a better way
@Module
public class TestModule{
@Provides
Bar provideBar(){
return new Bar();
}
@Provides
Foo provideFoo(Bar bar){
return new Foo(bar);
}
@Provides
Foo.Factory provideFooFactory(final Provider<Foo> fooProvider){
return new Foo.Factory(){
@Override
public Foo createNew() {
return fooProvider.get();
}
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With