我正在尝试重构我的代码,所以我在想Dagger2来解决我的问题。我已创建AppComponent
来存储我的所有Singletons
:
@AppScope
@Component(
modules = {
AppModule.class,
// more here...
}
)
public interface AppComponent {
Context exposeContext();
CmdComponent newCmdComponent(CmdModule module);
// ... few injections here
}
我的AppModule
:
@Module
public class AppModule {
private Context context;
public AppModule(Context context) {
this.context = context;
}
// ... provide appContext etc.
@AppScope @Provides
MyClass provideMyClass() {
Log.i("DAGGER", "provideMyClass: ");
return new MyClass();
}
}
我在我的Application
课程中注入了这个:
public class App extends Application {
private static AppComponent component;
@Override
public void onCreate() {
super.onCreate();
component = DaggerAppComponent.builder()
.appModule(new AppModule(app))
.build();
}
public static AppComponent getAppComponent() {
return component;
}
}
然后我的子组件CmdComponent
具有不同的@Scope
@CmdScope
@Subcomponent(
modules = {
CmdModule.class
}
)
public interface CmdComponent {
void inject(Cmd cmd);
}
现在我将依赖项注入我的Cmd
实例中,如:
@Inject MyClass myClass;
public Cmd() {
App.getAppComponent()
.newCmdComponent(new CmdModule())
.inject(this);
}
不幸的日志:Log.i("DAGGER", "provideMyClass: ");
和MyClass
构造函数中的日志多次显示...所以每次都会获得MyClass
的新实例。如何告诉Dagger每次都给我相同的实例(创建一次)?
答案 0 :(得分:0)
Ok. I solve my issue. The solution is simple. My AppScope
was created wrong. For some reason, I thought that annotation works like inheritance.
My custom annotation was like:
@Singleton
@Retention(RetentionPolicy.RUNTIME)
public @interface AppScope {
}
and Dagger thought that my component is unscoped.. It should be like:
@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface AppScope {
}
答案 1 :(得分:-1)
.newCmdComponent(new CmdModule())
怎么样?为什么这样做,每次创建一个新模块?该组件已经附加了一个模块,您可以在创建组件时设置该模块。