Reputation: 71
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
}
Upvotes: 7
Views: 10537
Reputation: 14444
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
Upvotes: 5
Reputation: 480
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.
Upvotes: 5