Sobes.tech
Junior — Middle

In which situations is it recommended to use the @Inject annotation for constructors when using Dagger?

sobes.tech AI

Answer from AI

The @Inject annotation for constructors in Dagger is recommended when you want Dagger to automatically create and provide instances of this class, managing its dependencies.

Situations for using @Inject on a constructor:

  • The class is a dependency that needs to be injected into other components.
  • The constructor does not require additional parameters that cannot be obtained through Dagger.
  • You want Dagger to automatically create objects without the need to manually write factories or modules.

Example:

public class UserRepository {
    private final ApiService apiService;

    @Inject
    public UserRepository(ApiService apiService) {
        this.apiService = apiService;
    }
}

Here, Dagger will know how to create UserRepository, automatically providing ApiService.

In which situations is it recommended to use the… - sobes.tech