2017-08-27 94 views
0

我想实现以下行为:模块混合示波器

  • 使用由模块下单的范围有不同的范围提供了另一个模块的对象。

这是我的。我尝试了很多基于几个答案的更改,但我仍然无法解决此问题。

第一模块(应绑定到应用程序的生命周期)

@Module 
public class AModule { 

private Context context; 

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

@Provides 
@Singleton 
MySharedPreference provideMySharedPreference(SharedPreferences prefs) { 
    return new MySharedPreferences(prefs); 
} 

@Provides 
@Singleton 
SharedPreference provideSharedPreference() { 
    return context.getSharedPreferences("prefs", 0); 
} 

它组分

@Component(modules = AModule.class) 
@Singleton 
public interface AComponent { 
    void inject(...); 
} 

第二模块(界到活动的生命周期)

@Module 
public class BModule { 

    @Provides 
    @ActivityScope 
    X provideX(MySharedPreferences prefs) { 
     return new Y(prefs); 
    } 
} 

它的部件

@Component(modules = BModule.class) 
@ActivityScope 
public interface BComponent { 
    Y Y(); 
} 

我宣布活动范围

@Scope 
@Retenion(RetentionPolicy.RUNTIME) 
public @interface ActivityScope{} 

而且MySharedPreferences是最后如下

public class MySharedPreferences { 

    private SharedPreferences mSharedPrefs; 

    @Inject 
    public MySharedPreferences(SharedPreferences prefs) { 
     mSharedPrefs = prefs; 
    } 

    // some methods 
} 

,在我的应用程序类,我创建了一个组件

aComponent = DaggerAComponent.builder().aModule(new AModule(getApplicationContext())).build(); 

编辑我试过的一些东西

我试着在BModule中加入includes = AModule.class。 我尝试将dependencies = AComponent.class添加到BComponent。 我试着用ActivityScope注释创建一个新的组件。

回答

1

如果您使用的是从属组件(dependencies =),则需要编写一个供应方法以将依存关系从@Singleton范围组件展示给@ActivityScope组件。

@Component(modules = AModule.class) 
@Singleton 
public interface AComponent { 
    void inject(...); 

    SharedPreferences exposeSharedPreferences(); 
} 

的提供方法将允许从属@ActivityScope组件使用@SingletonSharedPreferences绑定:

@Component(modules = BModule.class, dependencies = AComponent.class) 
@ActivityScope 
public interface BComponent { 
    Y Y(); 
} 

用于提供方法的更详细说明,请参见this question

+0

感谢您的回答!现在我明白了。我实际上已经尝试过类似的方法来解决问题,但现在更清楚了。 –