对于 Dagger 2,从其他模块访问 1 个模块内的实例的最佳方法是什么?

For Dagger 2, what is the best way to access an instance inside 1 module from other modules?

只是在 Android 应用程序中试用 Dagger 2,我觉得可能有一个更简单的解决方案来实现我想要实现的目标。

我有 2 个模块:

现在假设我有一个在 ApplicationModule 中创建的单例 Prefs 实例,但我需要在 UserModule 中的 类 中访问它,什么是解决这个问题的最好方法吗?目前我在 ApplicationModule 中创建它,然后在创建它时将其传递给 UserModule 的构造函数。有没有办法避免这样做并让 Dagger 为我管理它?

@Module
public class ApplicationModule {
    @Provides
    @Singleton
    public Prefs prefs() {
        return new Prefs();
    }
}

@Singleton
@Component(modules={ApplicationModule.class})
public interface ApplicationComponent {
    Prefs providePrefs();
}

@Module
public class UserModule {
    private Prefs prefs;

    public UserModule(Prefs prefs) {
        // Anyway to avoid having to do this?
        this.prefs = prefs;
    } 

    @Provides
    @UserScope
    public UserService userService() {
        // Possible to get the prefs from the ApplicationComponent?
        return new UserService(this.prefs);
    }
}

@Component(dependencies = {ApplicationComponent.class}, modules = {UserModule.class})
@UserScope
public interface UserComponent extends ApplicationComponent {
    UserService provideUserService();
}

dagger 的全部意义在于让它为您解决依赖关系。您不需要将任何不是直接需要的东西传递到您的模块中,例如用户模块的实际用户。

依赖将由匕首解决。在您的情况下,这意味着像这样调整您的代码:

@Module
public class UserModule {

    public UserModule() {
        // way of avoiding this code ;)
    }

    @Provides
    @UserScope
    public UserService userService(Prefs prefs) {
        return new UserService(prefs);
    }
}

这样 dagger 将提供对方法的依赖。你不必自己做。

这个工作的先决条件是可以实际提供依赖项。在您的情况下, Prefs 由应用程序组件提供。只要您实例化一个 @Subcomponent 或在您的情况下依赖 @Component 并公开依赖项,它就会起作用——应用程序组件中的 Prefs providePrefs() 方法。

如果提供依赖关系的模块在同一个组件中,这也将起作用。


如果你的 UserService 不依赖任何其他东西,你甚至可以考虑删除整个模块,因为它看起来可以通过构造函数注入来提供。

@UserScope
public class UserService {

    Prefs prefs;

    @Inject
    public UserService(Prefs prefs) {
        this.prefs = prefs;
    }
}