具有不同范围的模块

时间:2016-11-16 11:40:44

标签: android dagger-2

如何创建一个具有注释的模块,如@UserScope,依赖于另一个模块@Singleton?

@Module(includes = {ApplicationModule.class})
public class JobManagerModule
{
    private static final String TAG = JobManagerModule.class.getSimpleName();

    @UserScope
    @Provides
    public JobManager providesJobManager(final Context context)
    {
        Log.d(TAG, "Providing JobManager");
        final Configuration configuration = new Configuration.Builder(context).build();
        return new JobManager(configuration);
    }
}

这里,JobManagerModule使用@UserScope提供,但ApplicationModule提供Context对象(JobManagerModule需要)作为@Singleton。

这显示错误。

1 个答案:

答案 0 :(得分:3)

如果要创建不同的Scope,则此范围必须是@Singleton的子组件。

假设您ApplicationComponent注明了@Singleton

@Singleton
@Component(
        modules = ApplicationModule.class
)
public interface ApplicationComponent {

    JobManagerComponent provide(JobManagerModule jobManagerModule);
}

ApplicationModule提供Context

@Module
public class ApplicationModule {
    protected final Application mApplication;

    public ApplicationModule(Application application) {
        mApplication = application;
    }

    @Provides
    @ApplicationContext
    public Context provideApplicationContext() {
        return mApplication;
    }
}

请注意,ApplicationComponent必须提供JobManagerComponent  并且Context提供了@ApplicationContext注释。

现在,您将JobManagerComponent创建为@Subcomponent的{​​{1}}:

ApplicationComponent

@UserScope @Subcomponent( modules = JobManagerModule.class ) public interface JobManagerComponent{ }

JobManagerModule

请注意从@Module public class JobManagerModule { private static final String TAG = JobManagerModule.class.getSimpleName(); @UserScope @Provides public JobManager providesJobManager(@ApplicationContext Context context) { Log.d(TAG, "Providing JobManager"); final Configuration configuration = new Configuration.Builder(context).build(); return new JobManager(configuration); } } 注释中移除include,并使用@Module注释Context

创建@ApplicationContext

JobManagerComponent