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