3
当使用构造器注入与Dagger2,我真的可以看到如何依赖注入的概念实现的:活动现场注射用匕首2
public class Dependent {
@Inject
public Dependent(Dependency dependency) {
// We're dependent on an instance of the Dependency class
// but we don't care who provides it
}
}
但是,当涉及到Activity
,因为Android是实例对我们来说,我们需要使用Field Injection来满足我们的依赖关系。我在网上找到的所有示例都提示如下:
- 创建一个
@Module
类来提供我们的依赖关系。 - 创建一个
@Component
接口并调用generate builder来实例化它。大部分示例在Application
类中执行此操作,并将引用另存为成员。 - 在我们的
Activity
- 创建我们的@Inject
字段,并在onCreate(..)
方法中,从我们的Application
获得对Component
的引用并启动注入。
我的这种方法的问题是,它不觉得松散耦合,这是我们正在努力实现的。
public class DependentActivity extends Activity {
@Inject Dependency mDependency;
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MyApplication) getApplication()).getComponent().inject(this);
// We're dependent on an instance of dependency
// but now we not only know who provides it,
// we explicitly initiate the injection
}
}
我错过了什么?
所以猜我几乎明白了。谢谢你的回答,但我认为你所说的话有点乐观:你* *知道注射来自哪里,至少在表面上,但其余部分是真的 - 你不知道对象的创造并且可以切换出组件和模块。我猜想Dagger2的活动DI有一个活动的价格意识到它的注入器。好吧。支付小的价格。 –
“您可以切换出您的应用程序为您提供的组件类,并且您的活动不会改变。”完全正确 – AskQ