[英]How to instantiate an instance of our dependency graph in Dagger2
我正在學習dagger2
依賴注入框架。 我喜歡它如何注入依賴。 我讀了這篇文章https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2我看到那里他們在兩個Modules
的幫助下對此進行了解釋。
AppModule
和NetModule
是兩個Modules
。 兩者都有構造函數,因此它們實例化了依賴圖的實例,如下所示
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();
假設我還有一個沒有構造函數的Modules
,那么我將如何初始化它,因為其他2個模塊需要構造函數中的值?
謝謝
如果您的第三個模塊不需要構造函數,那么在@Component
的modules
列出它時,Dagger2會自動將其添加到component中,如下所示:
@Component(modules = {
AppModule.class,
NetModule.class,
ThirdModule.class // module without constructor
})
public interface NetComponent{
// ...
}
假設您的第三個模塊是TestModule:
您可以簡單地做到這一點:
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("https://api.github.com"))
.testModule(new TestModule())
.build();
注意:這里.testModule將給您不建議使用的警告,這意味着您甚至不必定義沒有構造函數的模塊。 它們被隱式添加到圖中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.