简体   繁体   中英

Avoid static context of application class using Dagger2 and MVVM

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);

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

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

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