除了我见过的有限示例之外,我很难理解如何使用 Dagger 2.0。让我们以阅读应用程序为例。在这个阅读应用程序中,有一个用户故事库和登录功能。本示例感兴趣的类别是:
MainApplication.java
- 扩展应用程序
LibraryManager.java
- 负责在用户库中添加/删除故事的经理。这是从MainApplication
AccountManager.java
- 负责保存所有用户登录信息的管理器。可以从 LibraryManager 调用
我仍在努力思考我应该创建哪些组件和模块。到目前为止,我可以收集到以下信息:
创建一个HelperModule
提供AccountManager
和LibraryManager
实例的:
@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);
}
包含@Injects LibraryManager libraryManager
在图中MainApplication
并将应用程序注入到图中。最后,它查询注入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();
...
}
}
但是问题是AccountManager
当我尝试在中使用它时它是空的LibraryManager
,我不明白为什么或如何解决这个问题。我在想这是因为MainApplication
注入到图中的那个没有直接使用 AccountManager,但是我需要如何将它注入LibraryManager
到图中吗?