简体   繁体   中英

how to inject dependency outside activity or fragment in Kodein or Koin?

want to initialize interface in a non activity or fragment class with Kodein DI Android

sample shows only hot to use Kodein inside activity, but not on the other parts

 class MainViewModel() :  KodeinAware{
   override val kodein by closestKodein()
   val repository : Repository by instance()
 }

in activity it works, but in other classes it shows error. I want to initialize interface inside another class

closestKodein only works in Android Context aware classes (such as fragments & activities). To use it outside of these classes, you need an Android context .

The android documentation clearly states:

Caution: A ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context.

[...]

If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.

Therefore, to access Kodein from a ViewModel:

class MainViewModel(app: Application) : ApplicationViewModel(app), KodeinAware {
    override val kodein = app.kodein
    val repository : Repository by instance()
}

Simpy pass a context or activity as param

override val kodein by closestKodein(context)

More info https://kodein.org/Kodein-DI/?5.0/android#_getting_a_kodein_object

Use it in any place. appKodein is global function.

val dataLayer: DataLayer = appKodein().instance()

override val kodein by kodein(activity!!)

class ReportViewModel(context: Context):ViewModel() ,KodeinAware
{
override val kodein by kodein(context)
val reportRepository:ReportRepository by instance()
}

My answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM