简体   繁体   中英

How to instantiate an instance of our dependency graph in Dagger2

I am learning dagger2 dependency injection framework. I loved it how it injects dependency. I read this article https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2 I see there they explained this with the help of two Modules .

AppModule & NetModule are the two Modules . Both has constructors, so they instantiate an instance of our dependency graph like this

 mNetComponent = DaggerNetComponent.builder()
                // list of modules that are part of this component need to be created here too
                .appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
                .netModule(new NetModule("https://api.github.com"))
                .build();

Suppose I have one more Modules which do not have a constructor then how would I initialize it, as other 2 modules need values in the constructor ?

Thanks

If your third module doesn't need a constructor Dagger2 will automatically add it to component if you list it in @Component 's modules like this:

 @Component(modules = {
     AppModule.class,
     NetModule.class,
     ThirdModule.class // module without constructor
 })
 public interface NetComponent{
     // ...
 }

Let's say your third module is TestModule:

you can simply do this:

 mNetComponent = DaggerNetComponent.builder()        
                .appModule(new AppModule(this)) 
                .netModule(new NetModule("https://api.github.com"))
                .testModule(new TestModule())
                .build();

Note: here .testModule will give you deprecated warning which means that you don't even have to define modules that have no constructors. They are implicitly added to the graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM