I'm using the dependency injection framework Koin in my app. The following line of code works perfectly in my MainActivity:
private val auth: FirebaseAuth by inject()
Unfortunately, the same line of code does not work in a custom BroadcastReceiver. Android Studio marks the "inject()"-function red and tells me it is an unresolved reference (import of "org.koin.android.ext.android.inject" is marked as unused).
When I try to build it nevertheless, I got the following exception:
Error:(14, 39) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: public inline fun ComponentCallbacks.inject(name: String = ...): Lazy defined in org.koin.android.ext.android
How can I make the injection work in this class and why does it fail?
The inject
method you use in Activities is defined here like so:
/**
* inject lazily given dependency for Android component
* @param name - bean name / optional
*/
inline fun <reified T> ComponentCallbacks.inject(name: String = "")
= lazy { (StandAloneContext.koinContext as KoinContext).get<T>(name) }
So you can call it in classes that implement the ComponentCallbacks
interface - these would be application components, like Activities or Services.
If you wish to use Koin the same way in your BroadcastReceiver, you can define another inject
extension on that class with the same implementation:
inline fun <reified T> BroadcastReceiver.inject(name: String = "")
= lazy { (StandAloneContext.koinContext as KoinContext).get<T>(name) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With