Search code examples
androiddagger-hilt

Hilt: Why is a class in ApplicationComponent scope created twice?


I'm using Hilt in a multi-module project and have a module with ApplicationComponent scope. I would expect everything provided by this module to be like a singleton and only created once during the lifetime of the application. However, I see the constructor of a provided class get called once in each activity. Here is a test setup:

MyModule.java:

@Module
@InstallIn(ApplicationComponent.class)
public abstract class MyModule {
  @Binds
  public abstract Foo providesDomain(MyFoo domain);
}

MyApplication.java:

@HiltAndroidApp
public class MyApplication extends MultiDexApplication {
  @Override
  public void onCreate() {
    super.onCreate();
  }
}

Each activity:

@AndroidEntryPoint
public class MyActivity extends AppCompatActivity {

  @Inject
  Foo foo;

MyFoo.java:

class MyFoo implements Foo {
  @Inject
  public MyFoo(@NonNull Application application) {
    Log.w("TEST", "My application: " + application);
  }
}

For each activity, the MyFoo constructor is called, but the application is the same. My understanding is that this should not happen with a module that is in ApplicationComponent scope. Why is MyFoo being created again?


Solution

  • I'm going to point myself to the relevant Android documentation: The class itself needs to be annotated with the scope.

    In the example above, MyFoo is only on the application scope if it is annotated like this:

    @Singleton
    class MyFoo implements Foo {
      @Inject
      public MyFoo(@NonNull Application application) {
        Log.w("TEST", "My application: " + application);
      }
    }