【发布时间】:2015-11-16 19:01:54
【问题描述】:
除了我见过的有限示例之外,我很难思考如何使用 Dagger 2.0。让我们以阅读应用程序为例。在这个阅读应用程序中,有一个用户故事库和登录功能。本示例感兴趣的类别是:
MainApplication.java - 扩展应用程序
LibraryManager.java - 负责在用户库中添加/删除故事的经理。这是从MainApplication 调用的
AccountManager.java - 负责保存所有用户登录信息的管理器。可以从 LibraryManager 中调用
我仍在努力思考应该创建哪些组件和模块。到目前为止,我可以收集到以下信息:
创建一个提供AccountManager 和LibraryManager 实例的HelperModule:
@Module
public class HelperModule {
@Provides
@Singleton
AccountManager provideAccountManager() {
return new AccountManager();
}
@Provides
@Singleton
LibraryManager provideLibraryManager() {
return new LibraryManager();
}
}
创建一个MainApplicationComponent,在其模块列表中列出HelperModule:
@Singleton
@Component(modules = {AppModule.class, HelperModule.class})
public interface MainApplicationComponent {
MainApplication injectApplication(MainApplication application);
}
在MainApplication 中包含@Injects LibraryManager libraryManager 并将应用程序注入到图中。最后它查询注入的LibraryManager 库中的故事数:
public class MainApplication extends Application {
@Inject LibraryManager libraryManager;
@Override
public void onCreate() {
super.onCreate();
component = DaggerMainApplicationComponent.builder()
.appModule(new AppModule(this))
.helperModule(new HelperModule())
.build();
component.injectApplication(this);
// Now that we have an injected LibraryManager instance, use it
libraryManager.getLibrary();
}
}
将AccountManager注入LibraryManager
public class LibraryManager {
@Inject AccountManager accountManager;
public int getNumStoriesInLibrary() {
String username = accountManager.getLoggedInUserName();
...
}
}
但是问题是当我尝试在LibraryManager 中使用AccountManager 时它为空,我不明白为什么或如何解决这个问题。我在想这是因为注入图表的MainApplication 没有直接使用AccountManager,但是我需要如何将LibraryManager 注入图表?
【问题讨论】:
-
顺便说一下,由于它没有参数,因此您不需要在组件构建器中包含 HelperModule。
-
@steffandroid 我也是这么想的,但是为什么 LibraryManager 中的 AccountManager 没有被初始化呢?