2017-07-29 26 views
2

我是使用Dagger和DI的新手。我正在嘗試使用AndroidInjection解析器將依賴關係注入到其活動的片段中。Android Dagger在任意時刻設置模塊

一般來說,我瞭解到,在使用Dagger.android的情況下,我必須創建MyAppComponent並安裝AndroidInjectionModule才能使用AndroidInjection.inject(Activity/Fragment/etc..)。通過這種方式,我提供了Subcomponents與Builders的接口,使Dagger能夠生成合適的注入器。

但是,如果我有子組件,即DeviceFragmentSubcomponent與具有參數化構造函數的模塊有依賴關係?

@Subcomponent(modules = {DeviceModule.class}) 
public interface DevicePageFragmentSubcomponent extends AndroidInjector<DevicePageFragment>{ 

    @Subcomponent.Builder 
    public abstract class Builder extends AndroidInjector.Builder<DevicePageFragment>{ 
     public abstract Builder setDeviceModule(DeviceModule deviceModule); 
    } 
} 

@Module 
public class DeviceModule { 

    private Device mDevice; 

    public DeviceModule(Device device) { 
     mDevice = device; 
    } 

    @Provides 
    public Device provideDevice(){ 
     return mDevice; 
    } 
} 

應該怎樣做對使用其片段AndroidInjection.inject(this)內DeviceActivity設置DeviceModule實例?

是否有可能在創建應用程序的依賴關係樹時添加所需的模塊,但對任意事件?

回答

0

Dagger的Android注入部分可以(當前)只能與AndroidInjection.inject(this)一起使用,它會在給定的Android Framework類型中注入一個預定義的模塊。

因此,沒有辦法傳入參數或模塊。

你的第一個選擇是不使用Dagger的Android注入部分。只要你認爲合適的創建你的組件,並注入你的對象。

第二種選擇是不使用參數/模塊。理論上,如果你的活動可以創建DeviceModule,Dagger也可以創建活動—,並且通過使用Android注入部分,注入類型的組件可以訪問它。

您沒有指定什麼依賴關係Device具有或爲什麼您需要將它從片段傳遞到DeviceModule

假設您的Device取決於DevicePageFragment

class Device { 
    @Inject Device(DevicePageFragment fragment) { /**/ } // inject the fragment directly 
} 

您可以訪問該片段並執行您將要執行的操作。如果這不是你的情況,假設你需要閱讀參數Bundle。您可以修改您的模塊以不使用設備,而是自行創建它,並擺脫構造函數參數。

@Module 
public class DeviceModule { 

    // no constructor, we create the object below 

    // again we take the fragment as dependency, so we have full access 
    @Provides 
    public Device provideDevice(DevicePageFragment fragment){ 
    // read your configuration from the fragment, w/e 
    long id = fragment.getArguments().getLong("id") 
    // create the device in the module 
    return new Device(id); 
    } 
} 

最後它真的取決於你的用例。


我試圖說明的是,您有權訪問您正在嘗試注入的對象。這意味着無論你在這個對象內能做什麼,你都可以在Dagger中完成。不需要參數化模塊,因爲您可以從目標中提取這些參數,如上所示。

+0

感謝您對dagger.android能力的澄清。我不會試圖這樣去。其實我已經在模塊中創建了封裝對象,並在Activity和Fragments之間共享這個對象。它現在滿足我的需求。是的,有很多選擇使用Dagger,我只是很好奇在創建依賴關係樹之後添加模塊,逐漸地。好的,它看起來就是答案) – atlascoder