简体   繁体   中英

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.

For example, I am using data binding. MainActivity::onCreate() gets ActivityMainBinding object after layout is inflated like this:

ActivityMainBinding binding = 
            DataBindingUtil.setContentView(this, R.layout.activity_main);

Now, how can I make this binding object available elsewhere through dagger module?

You can pass it to the module's constructor and return it (or something derived from it) from a @Provides method. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM