【发布时间】:2015-10-20 17:19:05
【问题描述】:
我正在尝试与另一个项目一起创建一个 Android 库,同时使用 Dagger 2 学习 DI。事实证明这比预期的要困难。
我的问题
我正在尝试使用一个名为 MySingleton 的单例类,我想从我的 Android 库和主应用程序中访问它。
当前设置
基本上,我的 Android 库项目中有一个名为 MySingleton 的单例类。在项目中,我有一个名为 SingletonModule 的类,它是一个 Dagger2 模块,提供我的单例。
@Provides @Singleton
MySingleton providesMySingleton() {
return new MySingleton();
}
好的,现在在我的实际应用中我有以下组件。
@Singleton
@Component(modules = {SingletonModule.class})
public interface ApplicationComponent {
void inject( MyApplication application );
}
所以这是用于将MySingleton 注入MyApplication 类。它就是这样做的。
this.applicationComponent = DaggerApplicationComponent.builder()
.singletonModule( new SingletonModule() ) // does it for you as empty constructor
.build();
applicationComponent.inject(this);
这很好,我通过字段注入的 MySingleton 实例运行良好。
我的尝试
在我的 Android 库项目中,我创建了一个名为 SingletonComponent 的新组件,它的功能与 ApplicationComponent 相同,只是提供了 MySingleton 对象。然后在扩展Service 的MyService 类中,我按字段注入了MySingleton 对象。这没有我想要的效果。它确实反对MySingleton 对象,但它与注入我的实际应用程序时创建的实例不同。我相信这是因为它是我正在创建的一个新组件...
我在这里做错了什么?
我查看了许多不同的网站并遵循了许多教程,但使用此依赖注入并没有点击。
【问题讨论】:
标签: android dependency-injection dagger-2