If you've been using Koin's DSL for dependency injection in your Kotlin Multiplatform projects, you might be interested in exploring a more annotation-driven approach. In this guide, Arnaud walks you through migrating a simple Compose Multiplatform application from Koin DSL to the new Koin Annotations 1.4.
We'll be working with the KMP App Template from JetBrains, which provides a great starting point for our exploration. The data displayed by the app is from The Metropolitan Museum of Art Collection API. This app already uses Koin for dependency injection. This template implements this simple art gallery application that displays a list of paintings and their details. While the functionality is straightforward, it serves as an excellent example to demonstrate Koin's annotation-based dependency injection. And bonus : it's beautiful to look at.
Before diving into the migration, let's ensure we have all the necessary dependencies:
Don't forget to set up KSP (Kotlin Symbol Processing) in your project, as it's essential for annotation processing.
Our sample application follows a clean architecture approach with the following key components:
MuseumAPI
: Handles remote data fetchingMuseumRepository
: Manages data operationsMuseumStorage
: Handles local data persistenceLet's start by migrating our view models from DSL to annotations. Replace the existing DSL module definition:
Next, let's tackle the data layer components:
For more complex scenarios where you need custom initialization logic, you can use separate functions with the @Single
annotation:
One of the powerful features of Koin Annotations is its support for platform-specific implementations. Here's how to set it up:
🔸 Cleaner Code: Annotations provide a more declarative and concise way to define dependencies
🔸 Better IDE Support: Enhanced code navigation and refactoring capabilities
🔸 Compile-Time Validation: Earlier detection of dependency injection issues
🔸 Reduced Boilerplate: KSP generates necessary extension functions automatically
🔸 Platform-Specific Support: Seamless handling of platform-specific dependencies
Migrating from Koin DSL to Annotations might require some initial setup, but the benefits in terms of code clarity and maintainability are well worth it. The annotation-based approach provides a more familiar paradigm for developers coming from other dependency injection frameworks while maintaining Koin's lightweight and Kotlin-first philosophy.
Remember to check out the official Koin documentation for more detailed information and advanced usage scenarios. Tell us what you think!