[英]How to add an object created elsewhere as dagger dependency?
I wonder how to add an object created elsewhere as dependency to be provided by dagger module. 我想知道如何添加在其他地方创建的对象作为由dagger模块提供的依赖项。
For example, I am using data binding. 例如,我正在使用数据绑定。
MainActivity::onCreate()
gets ActivityMainBinding
object after layout is inflated like this: 布局膨胀后,
MainActivity::onCreate()
获取ActivityMainBinding
对象,如下所示:
ActivityMainBinding binding =
DataBindingUtil.setContentView(this, R.layout.activity_main);
Now, how can I make this binding object available elsewhere through dagger module? 现在,如何通过dagger模块使此绑定对象可用?
You can pass it to the module's constructor and return it (or something derived from it) from a @Provides
method. 您可以将其传递给模块的构造函数,然后从
@Provides
方法返回它(或从它派生的东西)。 For example: 例如:
@AppScope
@Module
public class AppModule {
private final Context mContext;
public AppModule(@NonNull final Context context) {
mContext = context.getApplicationContext();
}
@Provides
@AppScope
Context provideApplicationContext() {
return mContext;
}
// more @Provides methods...
}
If you have activity-scoped dependencies, the activity can create a submodule using this same approach. 如果您具有活动范围的依赖项,则活动可以使用相同的方法来创建子模块。 Fragments can then get the activity's Dagger component and inject themselves.
然后,片段可以获取活动的Dagger组件并自行注入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.