让我们假设以下情况。有一个全局模块AppModule
, 范围模块 ScopedModule
, 一类Main
和一个类(class)Foo
在应用程序的主要变体中。此外,还有一个带有模块 DebugAppModule
的调试变体。 , 一个模块 DebugScopedModule
和一个类(class)Bar
.只有调试变体可能知道 Bar
.
主要变体包含以下相关代码摘录。
@Module AppModule { /*..*/ }
@Module(injects=Main.class, addsTo=AppModule.class)
ScopedModule { @Provides Foo provideFoo() { return new Foo(); } }
class Main { scopedGraph = graph.plus(new ScopedModule(this)); }
class Foo { /*..*/ }
// In the entry point of the application
ObjectGraph.create(new AppModule());
调试变体包含以下相关代码摘录。
@Module(addsTo=AppModule.class, overrides=true) DebugAppModule { /*..*/ }
@Module(injects=Main.class, addsTo=DebugAppModule.class, overrides=true)
DebugScopedModule { @Provides Foo provideFoo() { return new Bar(); } }
class Bar extends Foo { /*..*/ }
// In the entry point of the application
ObjectGraph.create(new AppModule(), new DebugAppModule());
我的研究和实验表明无法覆盖
@Provides
-作用域模块中的方法,即当plus
一个模块。参见示例 How to Mock Dagger Activity Object Graphs .也就是说,在调试变体中,只要 Foo
注入(inject)它仍然是 Foo
而不是 Bar
.这是有道理的,因为类 Main
对 ScopedModule
有固定的依赖关系(注意 new
)。在我看来,应该有一种方法可以自己注入(inject)作用域模块——可以说是元注入(inject):)。也就是说,
AppModule
可以提供ScopedModule
对于 Main
.问题是 ScopedModule
的构造函数需要 Main
的实例等等AppModule
需要保留 Main
的实例这不会飞(例如,在 Android 特定的上下文中,Main
将是一个 Activity)。那么实现覆盖
@Provides
效果的最佳替代方法是什么? - 使用作用域模块时的方法?
最佳答案
在最新版本的 Dagger 中,不允许覆盖 @Provided 方法。
我找到了一个很好的解决方案here .感谢@vaughandroid
基本上,
当您将模块提供到组件中时,您可以覆盖您的方法。
MyComponent component = DaggerMyComponent.builder()
.appModule(new AppModule() {
@Override public Foo provideFoo() {
return new Bar();
}
})
.build();
这对我有用,我想它对你有用。
关于dependency-injection - Dagger:覆盖作用域模块中的@Provides-Method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27639090/