热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Dagger2组件(无范围)不能依赖于范围组件-错误

如何解决《Dagger2组件(无范围)不能依赖于范围组件-错误》经验,为你挑选了1个好方法。

我正在尝试编译https://github.com/svenjacobs/android-dagger2-example 但我遇到了与未作用域组件相关的错误,具体取决于作用域组件.(Android Studio 1.1,Gradle 2.2.1).此外,如果有人知道其他Dagger2 Android示例与FRAGMENTS我想知道他们.

更新:这是另一个非常基本的片段示例:https: //github.com/gk5885/dagger-android-sample

/Users/Mac1/android-dagger2-example-master/app/src/main/java/com/svenjacobs/dagger2/ActivityComponent.java
Error:(15, 1) error: com.svenjacobs.dagger2.ActivityComponent (unscoped) cannot depend on scoped components:
@Singleton com.svenjacobs.dagger2.ApplicationComponent
Error:Execution failed for task ':app:compileDebugJava'.
> Compilation failed; see the compiler error output for details.

这是文件ActivityComponent,显然没有作用域:

import dagger.Component;

/**
 * Component for all activities.
 *
 * @author Sven Jacobs
 */
@Component(dependencies = ApplicationComponent.class,
       modules = {
               MainActivityModule.class,
               AModule.class,
               BModule.class
       })
interface ActivityComponent extends AFragment.Injector, BFragment.Injector  {

    void inject(MainActivity activity);

    void inject(AnotherActivity activity);
}

这是范围组件:

package com.svenjacobs.dagger2;

import javax.inject.Singleton;

import dagger.Component;

/**
 * Application-wide dependencies.
 *
 * @author Sven Jacobs
 */
@Singleton
@Component(modules = ApplicationModule.class)
interface ApplicationComponent {

void inject(Dagger2Application application);

/**
 * Provides dependency for sub-components
 */
SomeApplicationDependency someApplicationDependency();
  }

Adam Mcnabb.. 14

您需要为ApplicationComponent提供范围.这不一定是@Singleton,因为Dagger 2允许您使用界面上的@Qualifier注释定义自己的范围.

@Scope
public @interface CustomScopeName {
}

然后你可以像这样使用它:

@CustomScopeName
@Component(dependencies = ApplicationComponent.class,
   modules = {
           MainActivityModule.class,
           AModule.class,
           BModule.class
   }) .......

我认为不允许在未作用域组件中使用作用域依赖项的原因是为了防止Singletons依赖非Singleton对象并防止循环依赖.



1> Adam Mcnabb..:

您需要为ApplicationComponent提供范围.这不一定是@Singleton,因为Dagger 2允许您使用界面上的@Qualifier注释定义自己的范围.

@Scope
public @interface CustomScopeName {
}

然后你可以像这样使用它:

@CustomScopeName
@Component(dependencies = ApplicationComponent.class,
   modules = {
           MainActivityModule.class,
           AModule.class,
           BModule.class
   }) .......

我认为不允许在未作用域组件中使用作用域依赖项的原因是为了防止Singletons依赖非Singleton对象并防止循环依赖.


推荐阅读
author-avatar
张量扰动艹_712
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有