I have an interface called Animal. It has two implementations; Dog and Cat. Since I wanted to specify which implementation I want when injecting Animal in different objects I solved that in Hilt by doing the following:
@Module
@InstallIn(ApplicationComponent.class)
public abstract class ApplicationModule
{
@Named("Dog")
@Binds
public abstract Animal provideDog(Dog dog);
@Named("Cat")
@Binds
public abstract Animal provideCat(Cat cat);
}
Dog and Cat constructors have been annotated with @Inject:
public class Dog implements Animal
{
@Inject
public Dog()
{
}
}
public class Cat implements Animal
{
@Inject
public Cat()
{
}
}
If another class called C needs a Dog object:
public class C
{
@Inject
public C(@Named("Dog")Animal dog)
{
}
}
If another class called D needs a Cat object:
public class D
{
@Inject
public D(@Named("Cat")Animal cat)
{
}
}
When I run the app, I realized that Hilt always injects the same dog instance, meaning that that dog instance is shared among different instances of class C. What do I need to do If I wanted a new instance of dog for each instance of class C?
I did not add code for fields for brevity.