我已經在我的應用程序中設置了dagger2依賴項,並且通過很多示例瞭解它。我沒有找到的是一旦注入它們就可以使用所有依賴的正確方法。Dagger2使用整個依賴關係圖
模塊中的每個單例都依賴於之前單例的輸出。整個依賴關係圖是如何使用的,而不用調用每個單例來獲取所需的輸入?
考慮以下幾點:
AppComponent
@Singleton
@Component(modules = {
DownloaderModule.class
})
public interface AppComponent {
void inject(MyGameActivity activity);
}
DownloaderModule
@Module
public class DownloaderModule {
public static final String NETWORK_CACHE = "game_cache";
private static final int GLOBAL_TIMEOUT = 30; // seconds
public DownloaderModule(@NonNull String endpoint) {
this(HttpUrl.parse(endpoint));
}
@Provides @NonNull @Singleton
public HttpUrl getEndpoint() {
return this.endpoint;
}
@Provides @NonNull @Singleton @Named(NETWORK_CACHE)
public File getCacheDirectory(@NonNull Context context) {
return context.getDir(NETWORK_CACHE, Context.MODE_PRIVATE);
}
@Provides @NonNull @Singleton
public Cache getNetworkCache(@NonNull @Named(NETWORK_CACHE) File cacheDir) {
int cacheSize = 20 * 1024 * 1024; // 20 MiB
return new Cache(cacheDir, cacheSize);
}
@Provides @NonNull @Singleton
public OkHttpClient getHttpClient(@NonNull Cache cache) {
return new OkHttpClient.Builder()
.cache(cache)
.connectTimeout(GLOBAL_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(GLOBAL_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(GLOBAL_TIMEOUT, TimeUnit.SECONDS)
.build();
}
MyGameApp
public class MyGameApp extends Application {
private AppComponent component;
private static Context context;
public static MyGameApp get(@NonNull Context context) {
return (MyGameApp) context.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
component = buildComponent();
MyGameApp.context = getApplicationContext();
}
public AppComponent component() {
return component;
}
protected AppComponent buildComponent() {
return DaggerAppComponent.builder()
.downloaderModule(new DownloaderModule("https://bogus.com/"))
.build();
}
}
你是什麼意思,「取決於它之前的單身人士的產出」?看起來你的模塊結構良好,可以通過在相應的'@ Provide'方法中將每個部分作爲輸入參數來注入它需要的每個部分。你應該能夠注入'OkHttpClient'或者你從MyGameActivity中創建的任何其他依賴。 –
我只是無法在腦海中找到它。我讀了更多,概念正在沉入其中。令人沮喪的是有大量文章顯示如何設置它,但實際使用示例很難找到。現在我正在用一個體面的例子。謝謝。 –