【问题标题】:Dagger ObjectGraph plus() Modules that include modules in the root module keep returning No no-args constructorDagger ObjectGraph plus() 在根模块中包含模块的模块不断返回无参数构造函数
【发布时间】:2014-08-19 19:13:57
【问题描述】:

我有一个使用 Dagger 的 Android 应用。整个应用程序的某些部分我想为几个共享公共范围的活动添加范围对象图。以下模块位于根 ObjectGraph 中

@Module(
    injects = {
            MyApplication.class,
    },
    complete = false,
    library = true)
public class BasicContextManagerModule {

    private Context applicationContext;

    public BasicContextManagerModule(Context applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Provides
    Context getApplicationContext() {
        return applicationContext;
    }
}

然后我尝试通过existingObjectGraph.plus(new FileManagerModule());添加以下Module;

@Module(
    injects = {
            MyListActivity.class,
            MyFileDetailActivity.class,
            MyFileInfoActivity.class,
    },
    includes = BasicContextManagerModule.class
)
public class FileManagerModule {

    @Provides
    FileManager provideFileManager(Context context) {
        return new FileManager(context);
    }
}

但结果是

java.lang.UnsupportedOperationException: No no-args constructor com.myapp.core.modules.BasicContextManagerModule$$ModuleAdapter

有人可以帮我理解为什么加号不允许这样做吗?我从 dagger 文档中读到 plus 扩展了对象图,并且您可以拥有包含和添加到模块。但我一直没能做到这一点。

【问题讨论】:

    标签: android dependency-injection include square dagger


    【解决方案1】:

    includes 表示模块将存在于同一个子图中,如果您不传递实例,Dagger 将实例化它。

    addsTo 表示引用的模块应该在图中(实际上在父图中),但 Dagger 不会为您提供它。

    你想要的是addsTo

    【讨论】:

    • 嘿,Thomas,所以我按照你的建议做了,而且效果很好。但我想知道的是 FileManagerModule 添加到只提供上下文的模块,它是否会破坏只需要上下文而不需要文件管理器的地方的绑定?
    • 没有。当你的子图需要注入这样一个对象时,它会从父图获取上下文(如果对象是单例,它将被限定为子图,而不是父图)
    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2020-12-27
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多