1

使用 Dagger,对于简单的事情来说效果很好,但是当我将参数传递给模块时,我不明白规则。基本上是想将应用程序上下文传递给提供者方法,并创建一个需要上下文的 Volles 请求队列。

我像这样创建我的模块:

public static Object[] getModules(@ApplicationContext final Context appContext)
{
    return new Object[]{new ApplicationContextModule(appContext),new ReleaseModules()};
}

应用上下文模块:

@Module(library = true, includes = RequestQueueModule.class)
public final class ApplicationContextModule
{
    private final Context applicationContext;

    public ApplicationContextModule(final Context aContext)
    {
    Preconditions.checkNotNull(aContext, "Application Context");
    //
    applicationContext = aContext;
    }

    @ApplicationContext
    @Provides
    //@Singleton
    public Context provideApplicationContext()
    {
    return applicationContext;
    }
}

请求队列模块:

@Module(injects = {AutoCacheService.class, ServiceListFragment.class})
public class RequestQueueModule
{

    //private final Context context;

    //@Inject
    public RequestQueueModule()
    {
    //context = theContext;
    }

    @Singleton
    @Provides
    public com.android.volley.RequestQueue provideRequestQueue(@ApplicationContext final Context context)
    {
    return Volley.newRequestQueue(context);
    }
}

正如你所看到的,我玩了一些构造函数注入,看起来我想念第一次理解这一点。无论如何,使用 @ApplicationContext 注解来阐明应该注入 App Context。但我得到这个编译错误:

错误:com.app.android.application.modules.RequestQueueModule 的provideRequestQueue(android.content.Context) 需要@com.app.android.annotation.ApplicationContext()/android.content.Context 错误:com 上没有可注入成员。 android.volley.RequestQueue。你想添加一个可注入的构造函数吗?com.app.android.io.service.AutoCacheService 要求 com.app.android.application.modules.ReleaseModules

我花了几个小时来解决这个问题。但是真的看不出问题。我还尽量避免 library = true 开关,因为我的理解是它会在编译时禁用图形检查。一些食谱可以更好地理解这一点......

更新:看起来这个SO 问题与我的相似。

4

1 回答 1

0

像这样更新 RequestModule:

@Module(injects = {AutoCacheService.class, ServiceListFragment.class}, addsTo = ApplicationContextModule.class)
public class RequestQueueModule
{
}

这告诉 Dagger RequestQueueModule 添加到 ApplicationContextModule 并且可以访问该模块中提供的依赖项。这具有为您提供编译时验证的额外优势。

此语句将创建完整的图表:

ObjectGraph graph = ObjectGraph.create(new ApplicationContextModule(), new RequestQueueModule())

或者,您可以使用complete = falseRequestQueueModule,但这会将编译时可能捕获的任何错误推送到运行时。

于 2014-03-05T16:51:17.937 回答