Skip to Content
Course content

126: Dependency Injection with Koin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've probably heard the term "Dependency Injection" (DI) thrown around a thousand times. In a lot of tutorials, it's presented as this complex architectural requirement, often involving massive libraries like Dagger or Hilt that generate mountains of code you can't even see. But at its core, DI is just a fancy way of saying: "Don't let your classes create their own dependencies; give them what they need from the outside."

The Hard-Coded Trap

Let's look at a scenario we've all been in. Imagine you're building a feature to fetch user profiles. You have a UserRepository that needs a UserApi to make network calls and a UserDao to cache data locally. The naive way to do this is to instantiate those dependencies right inside the repository:

class UserRepository {
    private val api = UserApi()
    private val dao = UserDao()

    fun getUser(id: String): User {
        return dao.getCachedUser(id) ?: api.fetchUser(id).also { dao.save(it) }
    }
}

On the surface, this is clean. It just works. But you've just painted yourself into a corner. If you want to write a unit test for UserRepository, you can't. Why? Because every time you create a UserRepository, it spins up a real UserApi that tries to hit a real server. You can't swap it for a mock or a fake without changing the actual source code of the class. You've "hard-wired" your logic to your infrastructure.

The Manual Plumbing Headache

The next step is usually manual constructor injection. You move the dependencies to the constructor, which is a huge win for testing:

class UserRepository(private val api: UserApi, private val dao: UserDao) {
    // logic remains the same
}

Now your tests are easy—you just pass in a mock API. But now you've moved the problem. Instead of the UserRepository creating its dependencies, the ViewModel (or whatever calls the repository) has to do it. Then the Activity has to create the ViewModel. Suddenly, your app's entry point looks like a giant shopping list of object instantiations: val repo = UserRepository(UserApi(), UserDao()). As your app grows to 50 classes, this "manual plumbing" becomes a nightmare. You'll spend half your day just trying to figure out the order in which objects need to be created.

Letting Koin Handle the Graph

This is where Koin comes in. I like Koin because it's a "pragmatic" DI framework. It doesn't use annotation processing or code generation; it's just a DSL (Domain Specific Language) that lets you describe how your objects should be created. You define a module, and Koin keeps a map of how to provide those instances.

Here is how we'd translate our user feature into Koin:

val appModule = module {
    single { UserApi() }
    single { UserDao() }
    single { UserRepository(get(), get()) } 
}

Notice the get() function. This is Koin's magic. It tells Koin: "Look at the constructor of UserRepository, see that it needs a UserApi and a UserDao, and go find the definitions for those in your map." single creates a singleton, meaning the same instance is reused throughout the app's lifetime. If you wanted a fresh instance every time, you'd use factory instead.

The Trade-off: Runtime vs. Compile Time

I should be honest with you about the cost. Because Koin is a service locator under the hood and doesn't generate code at compile time, it can't tell you if you've forgotten to define a dependency until the app actually runs. If you call get() for a class you didn't put in a module, your app will crash with a NoBeanDefFoundException.

In a massive enterprise project with hundreds of developers, some people prefer Dagger because it catches these errors when you hit "Build." But for the vast majority of Kotlin projects, the simplicity of Koin—the lack of boilerplate and the incredibly fast build times—far outweighs the risk of a runtime crash that you would have caught in a basic smoke test anyway.

To use these dependencies in your classes, you just implement the KoinComponent interface and use inject(), which lazily retrieves the dependency the first time it's accessed:

class UserViewModel : KoinComponent {
    private val repository: UserRepository by inject()
    
    fun loadUser(id: String) {
        val user = repository.getUser(id)
        // update UI
    }
}



📋 Practical Task

Refactor the Payment Processing System

You have been handed a legacy PaymentService that is currently hard-coded and impossible to test. Your task is to refactor this into a Koin-managed system.

The Current Code:

class StripeGateway {
    fun process(amount: Double) = println("Processing \$$amount via Stripe")
}

class PaymentLogger {
    fun log(message: String) = println("LOG: $message")
}

class PaymentService {
    private val gateway = StripeGateway()
    private val logger = PaymentLogger()

    fun executePayment(amount: Double) {
        logger.log("Attempting payment of $amount")
        gateway.process(amount)
    }
}

Requirements:

  • Refactor PaymentService to use constructor injection for StripeGateway and PaymentLogger.
  • Create a Koin module named paymentModule that provides singletons for all three classes.
  • Ensure PaymentService is resolved using Koin's get() function within the module.
  • Demonstrate how you would instantiate PaymentService in a separate class (e.g., CheckoutController) using the by inject() delegate.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.