首页 > 解决方案 > 0Dagger 2:MVVM 无法确定模块范围

问题描述

我是 MVVM 和 Dagger 的新手,我正在尝试在我的应用程序中使用 Dagger 2 和 Butterknife 实现 MVVM。不幸的是,我收到以下错误:

error: @Modules cannot be scoped. Did you mean to scope a method instead?

当我尝试制作“ViewModelModule”单例时出现此错误。这是我的课:

@Singleton
@Module
public abstract class ViewModelModule { ... }

我在我的“ApplicationModule”中引用“ViewModelModule”,看起来像这样:

 @Singleton
 @Module(includes = ViewModelModule.class)
 public class ApplicationModule { ... }

如果我删除“Singleton”注释,一切正常。但我错过了什么?我究竟做错了什么?

标签: androidmvvmdagger-2

解决方案


模块不能是单例,单例可以是模块提供的依赖项。例如:

@Module
public class ViewModelModule { 
    @Provides 
    @Singleton
    public String provideFoo() {
        return "Foo";
    }
}

因此,@singleton从您的模块声明中删除注释。


推荐阅读