Search code examples
androiddependency-injectiondagger-2injectdagger

How to create activity context dependent object in dagger?


I have a situation, I have injected all objects using Dagger 2, But in one situation I am unable to rectify how to inject the object.

Following is the situation

mPager.setAdapter(new MyPagerAdapter(this));

Now in the above statement, I have to inject the MyPagerAdapter object using Dagger, but it requires current activity context.

So how to forward the activity context to the Dagger module?


Solution

  • (turning @EpicPandaForce's comment into an answer)

    You can write a module that takes an Activity in its constructor parameters like this:

    @Module
    @ActivityScope 
    public class MyModule {
        private final Activity activity;
    
        public MyModule(Activity activity) {
            this.activity = activity;
        }
    
        @Provides
        @ActivityScope
        Activity activity() {
            return activity;
        }
    }