Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a Factory with Dagger2

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?

like image 299
Addev Avatar asked Aug 07 '15 08:08

Addev


People also ask

What is dagger2 and why do you use it?

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.

What is factory in dagger?

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.

How does a dagger injection work?

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.


1 Answers

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();
                    }
        };
    }
}
like image 118
Addev Avatar answered Oct 04 '22 10:10

Addev