Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger: Field Injection in POJO

I never tried Guide or other DI library, but trying to use Dagger from square for Android application. It works great for Frgements, but not for POJO. The user guide assumes some knowledge on DI as it doesn't explain in greater detail. What should I do to inject restAdapater into my POJO. If I do field injection, with the same code, it works in Fragment.

public class MyApplication extends Application {
    private ObjectGraph objectGraph;

    @Override
    public void onCreate() {
        super.onCreate();
        objectGraph = ObjectGraph.create(new DIModule(this));

    }

    public ObjectGraph objectGraph() {
        return objectGraph;
    }

    public void inject(Object object) {
        objectGraph.inject(object);
    }

    ...
    @Module(entryPoints = { 
    MainActivity.class,  
    .....,
    Auth.class, 
    RestAdapter.class
    })
    static class DIModule {@Provides
        @Singleton
        public RestAdapter provideRestAdapter() {
            return new RestAdapter.Builder().setServer(
                    new Server(Const.BASE_URL)).build();
        }
    }
}

//POJO

public class Auth {

    @Inject
    RestAdapter restAdapater;


    String Username;
    String Password;

    public String authenticate() {
     ...

     Api api = restAdapater.create(..)  // **restAdapater is null**

     }
}

All the fragments are derived from the below, and DI works fine in them. In a recent talk by Eric burke, he explains this is necessary because Android constructs the object.

public class BaseFragment extends Fragment {
    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);

        ((MyApplication) getActivity()
                .getApplication())
                .inject(this);
    }

}
like image 257
bsr Avatar asked Dec 21 '25 09:12

bsr


1 Answers

If you create an Auth instance yourself, then Dagger wouldn't be aware of this instance and will not be able to inject the dependencies for you.

Since you have already declared Auth.class in the Module entryPoints, you just need to ask ObjectGraph for Auth instance:

Auth auth = objectGraph.get(Auth.class);

Dagger then would know what is required to provide an instance of Auth, i.e. inject it with your RestAdapter.

like image 85
paulboony Avatar answered Dec 22 '25 22:12

paulboony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!