Search code examples
androiddagger-2dagger-hilt

Inject custom Application class


I am using Hilt and am trying to inject my Application into another activity:

@HiltAndroidApp
public class MyApplication extends Application {
...
}

@AndroidEntryPoint
public class MyActivity extends AppCompatActivity {

    @Inject
    protected MyApplication application;
...
}

I am getting the following error:

error: [Dagger/MissingBinding] com.test.MyApplication cannot be provided without an @Inject constructor or an @Provides-annotated method.

I think I can write a provider for MyApplication, but I thought Hilt by default already does that. Assuming that I could inject the base "Application" class, but I would like to get my overridden application class. Without of course casting it every time I want to use it.


Solution

  • Hilt provides you only with Application class instance, this instance is seeded to the Singleton component after the plugin rewrites your MyApplication class.

    You can create your own module that will do the casting from Application object and reuse it by setting the module to work in Singleton component.

    @Module
    @InstallIn(Singleton::class)
    class MyApplicationModule {
        @Provides
        fun providesString(application: MyApplication): String {
            return application.toString()
        }
    
        @Provides fun providesMyApplicationInstance(application: Application) : MyApplication = application as MyApplication
    }