0

there are a sufficient number of DI frameworks in Kotlin's world that pursue one goal - to introduce dependency into the class. More to the point, my question is: why are these frameworks better than just doing this:

// UserService.kt
interface UserService {

    fun getUserById(id: String): User
}
// UserServiceImpl.kt
class UserServiceImpl : UserService {

    override fun getUserById(id: String): User = TODO()
}
// Components.kt
fun userService(): UserService = UserServiceImpl()
// UserOfUserService.kt
class UserOfUserService {

    private val userService = userService()
}

This is the most common example that came to my mind.

I know that DI frameworks offer more features than the example above. But in the term of an application with non-complex dependencies - is it possible to use this approach?

Thank you.

d1snin
  • 101
  • 1
  • 11
  • 4
    You can do DI without a DI framework. Of course in a trivial example with a single dependency, it's going to be hard to see the benefits. Real applications have hundreds of components which exist in a complex hierarchy. Wiring them all together is possible, it's just boilerplate-heavy and tedious. – Michael Mar 28 '22 at 14:14
  • Does this answer your question? [Why does one use dependency injection?](https://stackoverflow.com/questions/14301389/why-does-one-use-dependency-injection) – Karsten Gabriel Mar 28 '22 at 17:29
  • Hi, Karsten, not really, I know what DI is and its main purposes. All I wanted to know is whether it is possible to use a simple Factory Method as a DI tool within simple applications. Of course, as Michael pointed out, the DI Framework can be useful in applications with complex dependencies. So, I'll post the answer. – d1snin Mar 28 '22 at 19:12

1 Answers1

0

As Michael noted earlier, DI frameworks can be useful in the case of large applications with many dependencies, since it is much easier to delegate their management to the DI framework than to use even more confusing factories.

I wanted to know if my approach to using the factory method for small applications (or rather, libraries) is correct and got the answer, thank you.

d1snin
  • 101
  • 1
  • 11