Dagger 2 错误:如果没有 @Provides 注释的方法,则无法提供 android.content.Context

问题描述 投票:0回答:4

我正在努力在我的项目中实现 dagger 2。为此,我编写了以下几行代码:

@Inject
VideoControllerView mediaController;

@Module
public class PlayerModule {

    @Provides
    VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
        return new VideoControllerView(context, cntrls);
    }
}


@Component(modules = PlayerModule.class)
public interface PlayerComponent {
    VideoControllerView getVideoControllerView();
}

但是当我尝试编译我的应用程序时,我遇到了以下给定的错误:

Error:(14, 25) error: android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at
com.multitv.multitvplayersdk.module.PlayerModule.providesVideoControllerView(context, …)
com.multitv.multitvplayersdk.controls.VideoControllerView is provided at
com.multitv.multitvplayersdk.component.PlayerComponent.getVideoControllerView()

我已经四处寻找如何解决这个问题,但没有结果。请帮助我。

android dagger-2
4个回答
11
投票

请尝试理解错误。

PlayerModule.providesVideoControllerView(context, …)
需要上下文,但Dagger无法访问任何
Context
对象,因此它无法传入任何
Context
。因此,它会产生错误,告诉您它找不到任何
Context
,您应该添加一种方法来做到这一点。

如果没有 @Provides 注释的方法,则无法提供上下文。

因此...如果没有

context
带注释的方法,就无法提供
@Provides


确保您的

PlayerModule
所属的组件可以访问上下文。

将其作为 ApplicationComponent 的子组件,将 Context 添加到您的

PlayerModule
,将您的 Activity 实例绑定为 Context,等等

有很多方法可以做到这一点,但最终您需要在其中一个模块中使用如下方法:

@Provides Context provideContext() { return myContext; }

一旦 Dagger 找到

Context
,错误就会消失。


5
投票

你需要这样的模块:

@Module
public class ContextModule {

    private Context context;

    public ContextModule(Context context) {
        this.context = context;
    }

    @Provides
    @UefaApplicationScope
    Context provideContext() {
        return context;
    }
}

然后方法注入:

    @Provides
    @Inject
    VideoControllerView providesVideoControllerView(Context context, VideoControllerView.Controlers cntrls) {
        return new VideoControllerView(context, cntrls);
    }

1
投票

在我的例子中,我试图将

DataModule.kt
类从应用程序模块迁移到库模块,我只需在迁移后在
DataModule.kt
中添加此方法即可使其能够找到上下文:

    @Provides
    fun provideContext(
        @ApplicationContext context: Context,
    ): Context {
        return context
    }


0
投票

我使用

@ApplicationContext
注释来修复它:

@Inject
@ApplicationContext
lateinit var appContext: Context
© www.soinside.com 2019 - 2024. All rights reserved.