I am using Dagger 2 and have it working however I now need access to the Android Application Context.
Its not clear to me how to inject and get access to the context. I have tried to do this as follows:
@Module public class MainActivityModule { private final Context context; MainActivityModule(Context context) { this.context = context; } @Provides @Singleton Context provideContext() { return context; } }
However this results in the following exception:
java.lang.RuntimeException: Unable to create application : java.lang.IllegalStateException: mainActivityModule must be set
If I inspect the Dagger generated code this exception is raised here:
public Graph build() { if (mainActivityModule == null) { throw new IllegalStateException("mainActivityModule must be set"); } return new DaggerGraph(this); }
I am not sure if this is the correct way to get Context injected - any help will be greatly appreciated.
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
You pass the dependencies of a class to its constructor. Field Injection (or Setter Injection). Certain Android framework classes such as activities and fragments are instantiated by the system, so constructor injection is not possible. With field injection, dependencies are instantiated after the class is created.
The @Singleton annotation is used to declare to Dagger that the provided object is to be only initialized only once during the entire lifecycle of the Component which uses that Module.
Dagger automatically generates code that mimics the code you would otherwise have hand-written. Because the code is generated at compile time, it's traceable and more performant than other reflection-based solutions such as Guice. Note: Use Hilt for dependency injection on Android.
@Module public class MainActivityModule { private final Context context; public MainActivityModule (Context context) { this.context = context; } @Provides //scope is not necessary for parameters stored within the module public Context context() { return context; } } @Component(modules={MainActivityModule.class}) @Singleton public interface MainActivityComponent { Context context(); void inject(MainActivity mainActivity); }
And then
MainActivityComponent mainActivityComponent = DaggerMainActivityComponent.builder() .mainActivityModule(new MainActivityModule(MainActivity.this)) .build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With