如何在 Dagger2 中实例化我们的依赖图实例
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 个模块需要构造函数中的值?
谢谢
假设您的第三个模块是 TestModule:
你可以简单地这样做:
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("https://api.github.com"))
.testModule(new TestModule())
.build();
注意:这里的 .testModule 会给你 deprecated 警告,这意味着你甚至不必定义没有构造函数的模块。它们被隐式添加到图表中。
如果你的第三个模块不需要构造函数,如果你像这样在 @Component
的 modules
中列出它,Dagger2 会自动将它添加到组件中:
@Component(modules = {
AppModule.class,
NetModule.class,
ThirdModule.class // module without constructor
})
public interface NetComponent{
// ...
}
我正在学习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 个模块需要构造函数中的值?
谢谢
假设您的第三个模块是 TestModule:
你可以简单地这样做:
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("https://api.github.com"))
.testModule(new TestModule())
.build();
注意:这里的 .testModule 会给你 deprecated 警告,这意味着你甚至不必定义没有构造函数的模块。它们被隐式添加到图表中。
如果你的第三个模块不需要构造函数,如果你像这样在 @Component
的 modules
中列出它,Dagger2 会自动将它添加到组件中:
@Component(modules = {
AppModule.class,
NetModule.class,
ThirdModule.class // module without constructor
})
public interface NetComponent{
// ...
}