6

I want to inject application string inside object class SingletonObject. I am new in Hilt and not getting any way to inject this

object SinglentonObject{
    @AppQualifier
    @Inject
    lateinit var applicationString: String
}
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37

2 Answers2

4

The @Inject annotation is available only for EntryPoints like @AndroidEntryPoint, @HiltAndroidApp. As of now, there is no option to inject into a non-entry point classes in Hilt.

Alexander
  • 450
  • 5
  • 16
3

You can't use the @Inject annotation but, if you still want to have a single source of truth and use Hilt from anywhere, you can create a custom EntryPoint and then use the ApplicationContext to grab an instance of whatever you are providing with Hilt.

First, you have to declare the EntryPoint (it can be added anywhere you want, but the best practice is to keep it closer to where it's used):

@EntryPoint
@InstallIn(SingletonComponent::class)
interface ApplicationStringInterface {
  @AppQualifier fun getApplicationString(): String
}

then you can grab an instance of the ApplicationString like this:

var applicationString = EntryPoints.get(applicationContext, ApplicationStringInterface::class.java).getApplicationString();

If you need help to get an instance of the applicationContext from anywhere, look here: https://stackoverflow.com/a/54076015/293878

Roberto Leinardi
  • 10,641
  • 6
  • 65
  • 69