dependency-injection - 带有构造函数参数的 Dagger 模块?

标签 dependency-injection dagger

在 Guice 中,我可以完全控制何时构建模块,并使用一些带有我安装的构造函数参数的模块。

然而,在 Dagger 中,引用其他模块的方法是通过 @Module 包含注释,并且没有向我提供创建要安装的模块的相同方法。

是否可以从具有构造函数参数的多个模块创建一个健全的 ObjectGraph?尤其是可以与 dagger-compiler 一起使用,并且不会遇到循环图的?

最佳答案

如果您有多个模块使用相同的对象,那么也许您应该将该对象分离到它自己的模块中。例如,很多模块使用应用程序上下文,所以我有以下模块:

@Module
public class ContextModule {

    private final Context mContext;

    public ContextModule(Context context) {
        mContext = context;
    }

    @Provides
    public Context provideContext() {
        return mContext;
    }

}

所以现在在其他模块中,当我需要一个上下文对象时,我只包含该模块。

例如:
@Module(entryPoints = { MyFragment.class }, includes = { ContextModule.class })
public class ServicesModule {

    @Provides
    public LocationManager provideLocationManager(Context context) {

        return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    @Provides
    public Geocoder provideGeocoder(Context context) {
        return new Geocoder(context);
    }
}

然后,当我构造对象图时,我最终只得到一个将应用程序上下文作为参数的模块。

关于dependency-injection - 带有构造函数参数的 Dagger 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15846349/

相关文章:

Scala 蛋糕模式和自类型注释

java - 使用类似于 Spring 的 Guice 将属性注入(inject)到像 VelocityEngineFactoryBean 这样的类中

dependency-injection - 如何在 .NET Core 的该层绑定(bind)服务 dll 的依赖项

Android - 运行时 Dagger 注入(inject)

android - JUnit TestRule 中的 Dagger 注入(inject)

c# - 如何在 .Net 核心控制台应用程序中使用依赖注入(inject)

c# - 如何在后台任务中使用具有依赖性的作用域服务

android - Dagger 组件 : error: cannot find symbol kotlin classes

android - LiveData 在第一次调用后没有更新它的值

android - Dagger 2 : Module must be set