How to use dagger in a android library project

后端 未结 3 1047
梦如初夏
梦如初夏 2020-12-08 00:23

I\'m currently trying to add Dagger to my android projects. For the apps projects its easy and clear to me, how to build the ObjectGraph. But I dont quite know whats the bes

3条回答
  •  没有蜡笔的小新
    2020-12-08 01:03

    I'm doing this way:

    1. @Module classes belong to the main project and they provide implementations which you are injecting to library elements, so there are no @Module classes in the library projects

    2. Library elements which are expecting dependency must have access to ObjectGraph and call .inject() on themselves, but main project should give ObjectGraph instance to the library with provided @Module dependency

    3. How to get ObjectGraph from main project into the library? You could have interface like this:

      interface Injector {
          void inject(Object object);
          public ObjectGraph getObjectGraph(); 
      }

    Context objects like Activity or Application class implements this interface (holders of ObjectGraph objects).

    If you have example of Activity in the library module which needs something to inject from the main project this would look like this:

    class LibraryActivity extends Activity {
    
        @Inject ActivationModule instance;
    
        void onCreate(... ) {
            Injector injector = (Injector)getApplicationContext();
            injector.inject(this)
        }
    }
    

    ActivationModule is the class/interface in the library project.

    Main project has application class which implements Injector interface and creates ObjectGraph with provided dependecy for ActivationModule in the library project.

    class MyApplicationInTheMainProject extends Application implements Injector {
    
        ObjectGraph graph;
    
        @Override
        public void onCreate() {
            super.onCreate();
            graph = ObjectGraph.create(new ActivationModuleImpl(this));
        }
    
        @Override public void inject(Object object) {
            graph.inject(object);
        }
    
        @Override public ObjectGraph getObjectGraph() {
            return graph;
        }
    }
    
    
    @Module(injects = {
            LibraryActivity.class
    }, library = true)
    class ActivationModuleImpl implements ActivationModule {
        ....
    }
    

提交回复
热议问题