내 응용 프로그램에서 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();
}
}
"이전에 싱글 톤의 출력에 달려 있습니까?" 모듈은 각 조각을 해당'@ Provides' 메서드의 입력 매개 변수로 가져 와서 필요한 각 요소를 주입 할 수 있도록 잘 구조화 된 것 같습니다. MyGameActivity 내에서 생성 한'OkHttpClient' 나 다른 의존성을 삽입 할 수 있어야합니다. –
나는 머리에 곧바로 직면하는 데 어려움을 겪고있다. 좀 더 읽고 개념이 침몰하고 있습니다. 실망한 것은 설정하는 방법을 보여주는 수많은 기사가 있지만 실제 사용 예제를 찾기가 어렵습니다. 나는 괜찮은 모범을 보이고있다. 감사. –