7

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?

Piwo
  • 1,347
  • 1
  • 12
  • 19

1 Answers1

13

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) }
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • 2
    This works well, but to be more generic I left out the Receiver completly, so that inject() can be used in everywhere – Piwo Jan 18 '18 at 15:02
  • Yeah, that seems reasonable as well. I'm not sure why it's defined on `ComponentCallbacks` to begin with, since it doesn't make use of a `Context` or anything like that. I suppose it's only so that it doesn't pollute the global namespace with a new method that's usually used in specific classes only.. – zsmb13 Jan 18 '18 at 15:04
  • 1
    Take a look for this answer:https://stackoverflow.com/a/55675198/5643911 – ininmm Jun 15 '20 at 01:07