Dagger 2 injection in non Activity Java class

ぃ、小莉子 提交于 2019-12-02 16:44:44

You should generally use constructor injection whenever possible. The call to component.inject(myObject) is mostly to be used for objects which you can not instantiate yourself (like activities or fragments).

Constructor injection is basically what you already did:

private class MyManager {
    private SharedPreferencesManager manager;

    @Inject
    MyManager(SharedPreferencesManager manager){
          this.manager = manager;           
    } 
}

Dagger will create the object for you and pass in your SharedPreferencesManager. There is no need to call init or something similar.

The real question is how to obtain an object of MyManager. To do so, again, dagger will handle it for you.

By annotating the constructor with @Inject you tell dagger how it can create an object of that type. To use it, just inject it or declare it as a dependency.

private class MyActivity extends Activity {
    @Inject
    MyManager manager;

    public void onCreate(Bundle savedState){
        component.inject(this);  
    } 
}

Or just add a getter to a component (as long as SharedPreferenceManager can be provided, MyManager can also be instantiated):

@Component(dependencies = SharedPreferenceManagerProvidingComponent.class)
public interface MyComponent {

    MyManager getMyManager();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!