2016-12-01 63 views
6

我對匕首2很新。我試圖在我的Android項目中實現它。 我有一個Service需要GoogleApiClient。我正在使用Dagger將其注入此服務中。匕首2:組件依賴於多個作用域組件

@FragmentScoped 
@Component(dependencies = {NetComponent.class, RepositoryComponent.class}) 
public interface CustomServiceComponent { 
    void inject(CustomService customService); 
} 

@Singleton 
@Component(modules = {AppModule.class, NetModule.class}) 
public interface NetComponent { 
    GoogleApiClient getGoogleApiClient(); 
} 

@Singleton 
@Component(modules = {AppModule.class, RepositoryModule.class}) 
public interface RepositoryComponent { 
    DatabaseService getDatabaseService(); 
} 

AppModuleNetModule,並RepositoryModule有方法標記@Singleton @Provides 當我建立我的項目,我得到這個錯誤:

The locationServiceComponent depends on more than one scoped component: @Singleton NetComponent @Singleton RepositoryComponent

我明白我的LocationComponent不能取決於兩個@Singleton範圍的組成部分,但我需要兩個他們在我的服務和都需要是@Singleton

有沒有更好的選擇做同樣的事情?

+0

「我明白我的LocationComponent不能依賴於兩個@Singleton作用域組件」 - >你能解釋爲什麼這是不可能的嗎? –

回答

6

請注意,雖然您可能有多個標記爲@Singleton的組件,但它們的生命週期將遵循那些保留組件參考的類。

這意味着如果您在活動中初始化並保留您的NetComponentRepositoryComponent,它將遵循該活動的生命週期,並且不會真正成爲應用程序單身人士。

因此,在Android應用程序中,您可能不需要超過一個@Singleton組件。考慮你的兩個單身的組件組合成一個組件是這樣的:

@Component(modules = {AppModule.class, NetModule.class, RepositoryModule.class}) 
@Singleton 
public interface AppComponent { 
    GoogleApiClient getGoogleApiClient(); 

    DatabaseService getDatabaseService(); 
} 

然後確保你的應用程序級保留此@Singleton組件,並使其可用於相關組件使用,這些在片段或活動的水平初始化。

public class MyApp extends Application { 

    private final AppComponent appComponent; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     appComponent = DaggerAppComponent.builder() 
          //modules if necessary 
          .build(); 
    } 

    public AppComponent getAppComponent() { 
     return appComponent; 
    }     
} 

需要注意的是,只要你的@FragmentScoped沒有任何依賴組件本身,你仍然可以創建儘可能多的這些,只要你喜歡。

請注意,即使單個組件現在注入GoogleApiClientDatabaseService,您仍然可以實現關注點的分離,因爲它們是在單獨的Dagger 2模塊中提供的。

+0

這個解決方案很髒。您的AppComponent共享所有模塊,取而代之,我希望能夠根據所需配置和所提供組件的需要,從其他許多組件構建我的組件。怎麼做?孤島危機引入井結構 – murt

+0

@ murt他試圖在非單例範圍內提供單例依賴關係。這是行不通的。你是對的,他需要重組,但他需要按範圍對組件進行分組 - 一個應用程序範圍的組件,然後是活動或片段級別的子組件或相關組件。 –

+0

@ murt您可以使用依賴組件查看一些其他答案https://stackoverflow.com/a/40751767/5241933 –