0

I want to start using dagger 2 for my side project I am working on.

An android application using MVVM design pattern. I use Dagger 2 as a dependency injection tool. It does the job but generally I need a lot of injections inside my (Models). The only way I found to do the job is to have an static instance of Application class that I do once I create it.

So I can inject it on the Model layer, where I do not have activity or application context. I am wondering is this the correct way of doing it or I am wrong?

//Inside Application class

    private static Context context;
    public static Context getContext() {
       return context;
    }


 //Inside Model class   
((MainApplication)MainApplication.getContext()).getMyComponent().inject(this);
Kishan Viramgama
  • 893
  • 1
  • 11
  • 23
EdinTAm
  • 5
  • 3

2 Answers2

0

make a app level component and provide context as DI. in your activity level component provide app level dependency as downstream

rahul khurana
  • 188
  • 1
  • 9
0

Working example; Injecting Application Context into Activities.

   @Component
   @module({AppModule.class})
   public interface ApplicationComponent {
            @ApplicationContext
            Context getApplicationContext();

            void inject(MyActivity activity);
    } 

/* Qualifiers */
import javax.inject.Qualifier;

@Qualifier
public @interface ApplicationContext {
}

/* app Module */
import dagger.Module;

@Module
public class AppModule {
    private Context appContext;
    public AppModule(@ApplicationContext Context _context) {
        this.appContext = _context;
    }
}

Now in your Application class; you will have to create Dagger Tree;

public static ApplicationComponent appCompnent;

@Override
void onCreate() {
     appCompnent = ApplicationComponent.builder().appModule(new AppModule(this)).create();
 }


 public static ApplicationComponent getApplicationComponent() {
     return appComponent;
   }

Now in your MyActivity; all you need is get this component and call inject.

I've a post in which I've listed out basic of Dagger2 and some study links hope that helps

Not able to understand dagger dependency injection concepts - Dagger 2 on android

Jileshl
  • 146
  • 6