I inject
viewModels
,repositories
,fragments
,Utils
and ... but Is it good way to inject
common class
with dependency injection
Koin
or Dagger-hilt
?
Suppose that we want to use StringBuilder()
class in fragment
First approach :
We can inject
it
val otherModule= module {
single { StringBuilder() }
}
And use it in fragment
like this :
class Fragment : BaseFragment(){
private val mPassword : StringBuilder by inject()
}
Second approach :
We can create new
instance
without injection
class Fragment : BaseFragment(){
private var mPassword = StringBuilder()
}
My question is the first approach is common way for us ?
I'd say that it depends. The main goal / concept behind Di is to fulfil the firth principle of S.O.L.I.D, or as freecodecamp.org says:
Another good answer is provided here, as it is already discussed when not to use dependency injection.
And now my opinion: If possible, try to inject those dependencies that you have to use quite often and if possible, inject them via constructor injection. With this, you can easily see, which dependencies are used by your class. Try not to inject classes that are used once or common language classes.