We are building a mobile app, so we are in the context of Android development, but the concept of dependency injection (DI) is universal.
Let's break down the question:
- What is dependency injection?
- What problem does dependency injection solve? (Tight coupling)
- Show a "before" example where a class creates its own dependency.
- Show an "after" example where the dependency is injected (e.g., via the constructor).
- What is a DI framework? (e.g., Dagger, Hilt, Koin for Android/Kotlin)
- What benefits does a DI framework provide?
Let's answer step by step.
1. What is dependency injection?
Dependency injection is a design pattern in which an object receives other objects that it depends on (called dependencies) from an external source rather than creating them itself.
2. What problem does dependency injection solve? (Tight coupling)
Without DI, a class might create its own dependencies (e.g., by instantiating them with new or using a factory). This leads to tight coupling because the class is directly dependent on the concrete implementation of the dependency. This makes the code:
- Hard to test (because you cannot easily replace the dependency with a mock or stub)
- Less flexible (changing the dependency requires changing the class that uses it)
- Violates the Dependency Inversion Principle (a part of SOLID) because the high-level module depends on low-level modules.
DI solves this by inverting the control of creating dependencies: the dependencies are provided (injected) to the class from the outside, typically by a framework or a factory.
3. "Before" example: class creates its own dependency
Let's consider a simple example in Kotlin for an Android app: a UserRepository that uses a UserService to fetch user data.
Without DI:
class UserRepository {
private val userService = UserService() // creates its own dependency
fun getUser(id: String): User {
return userService.fetchUser(id)
}
}
class UserService {
fun fetchUser(id: String): User {
// ... makes network call or database query
}
}
Here, UserRepository is tightly coupled to UserService. We cannot easily replace UserService with a different implementation (e.g., a mock for testing).
4. "After" example: dependency injected via constructor
With DI, we inject the dependency through the constructor (or setter, but constructor injection is preferred for immutability and mandatory dependencies).
class UserRepository(private val userService: UserService) { // dependency is injected
fun getUser(id: String): User {
return userService.fetchUser(id)
}
}
// Now, we can create the repository with any UserService implementation:
val realService = UserService()
val repository = UserRepository(realService)
// Or for testing:
val mockService = MockUserService()
val testRepository = UserRepository(mockService)
This makes UserRepository depend only on an abstraction (the type of userService), and we can provide any implementation.
5. What is a DI framework? (e.g., Dagger, Hilt, Koin)
In a large app, manually creating and passing dependencies can become complex, especially when there are multiple layers and dependencies have their own dependencies (a dependency graph). A DI framework automates the process of creating and providing dependencies.
- Dagger (and Hilt, which is a wrapper around Dagger for Android) and Koin are popular DI frameworks for Android/Kotlin.
They allow you to declare how dependencies are provided (using modules, annotations, or DSL) and then generate code (or use runtime reflection in Koin's case) to create the dependency graph and inject it into the classes that need it.
Example with Hilt (a simplified version):
First, set up Hilt in your project (with annotations and annotations processing).
Then, we can annotate our UserService to be provided by Hilt:
@Singleton
class UserService @Inject constructor() {
// ...
}
And then we can inject UserService into UserRepository:
@Singleton
class UserRepository @Inject constructor(
private val userService: UserService
) {
// ...
}
Hilt will then generate the code to provide an instance of UserService (as a singleton) and inject it into UserRepository.
With Koin, we define modules:
val appModule = module {
single { UserService() }
factory { UserRepository(get()) }
}
And then we can inject UserRepository in an Activity (for example) by:
class MainActivity : AppCompatActivity() {
private val repository: UserRepository by inject()
}
6. What benefits does a DI framework provide?
- Automatic dependency management: The framework builds the dependency graph and provides instances where needed, reducing boilerplate code.
- Scoping: You can define the scope of dependencies (e.g., singleton, activity-scoped, etc.)
- Lifecycle awareness: In Android, frameworks like Hilt integrate with the Android lifecycle (e.g., providing activity-scoped or viewModel-scoped dependencies).
- Easier testing: As shown, we can replace implementations with mocks easily, especially when using constructor injection. The framework can also be configured to provide test dependencies.
- Reduces coupling: The classes only depend on abstractions (interfaces) and not on concrete implementations.
- Reusability and modularity: Dependencies can be reused across different parts of the app and modules (especially in multi-module projects).
However, note that using a DI framework adds complexity and build time (for compile-time frameworks like Dagger) and might have a learning curve.
Summary
Dependency injection is a pattern that promotes loose coupling by injecting dependencies from the outside. It solves the problem of tight coupling, making code more testable, flexible, and maintainable. DI frameworks like Hilt and Koin automate the process of creating and managing the dependency graph, providing additional benefits like scoping and lifecycle management.
What is Dependency Injection?
Dependency Injection (DI) is a design pattern where dependencies (services/objects) are provided to a class from an external source, rather than the class creating them itself. It inverts control of dependency creation — moving it from inside the class to an outside injector.
Problem It Solves: Tight Coupling
When a class instantiates its own dependencies (e.g., val repo = UserRepository() inside another class), it becomes tightly coupled to:
- Concrete implementations (hard to swap out, e.g., for testing or different environments).
- Construction logic (changes to a dependency require modifying the class).
- Lifecycle management (who controls creation/destruction?).
This violates the Dependency Inversion Principle (high-level modules shouldn’t depend on low-level modules; both should depend on abstractions).
"Before" Example: Self-Created Dependency (Tight Coupling)
// Tightly coupled class
class UserViewModel {
// BAD: Creates its own dependency
private val userRepository = UserRepository()
fun loadUser(userId: String) {
val user = userRepository.getUser(userId)
// ... update UI state
}
}
class UserRepository {
fun getUser(userId: String): User {
// Real network/database call
}
}
Issues:
- Cannot replace
UserRepository with a mock/fake for testing.
UserViewModel is forever tied to UserRepository.
- If
UserRepository needs a parameter (e.g., ApiService), you must modify UserViewModel.
"After" Example: Injected Dependency (Loose Coupling)
// Loosely coupled class
class UserViewModel(private val userRepository: UserRepository) {
// Dependency is INJECTED via constructor
fun loadUser(userId: String) {
val user = userRepository.getUser(userId)
// ... update UI state
}
}
// Same UserRepository (no changes needed)
class UserRepository {
fun getUser(userId: String): User { /* ... */ }
}
// Usage (now flexible):
val realRepo = UserRepository()
val realViewModel = UserViewModel(realRepo) // Inject real dependency
// For testing:
val mockRepo = FakeUserRepository() // Or Mockito.mock()
val testViewModel = UserViewModel(mockRepo) // Inject mock
Benefits:
UserViewModel depends only on the abstraction (UserRepository interface, though we used a concrete class here—better would be to inject an interface).
- Testable with fakes/mocks.
- Single Responsibility:
UserViewModel doesn’t manage dependency creation.
What is a DI Framework?
A DI framework automates dependency creation and injection by:
- Managing the dependency graph: Builds objects in the correct order, resolving dependencies recursively.
- Providing scopes: Defines lifetimes (e.g.,
@Singleton, @ActivityScoped).
- Generating code: At compile time (Dagger/Hilt) or runtime (Koin) to wire dependencies.
Popular Android/Kotlin DI Frameworks:
- Dagger 2 (compile-time, annotation-based, strict but powerful)
- Hilt (simplifies Dagger for Android with pre-defined components/scopes)
- Koin (DSL-based, runtime, easier setup, less boilerplate)
- Kodein (similar to Koin, multiplatform)
Example with Hilt (Android)
// 1. Define dependencies with @Module
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideUserRepository(apiService: ApiService): UserRepository {
return UserRepository(apiService)
}
}
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideApiService(): ApiService {
return Retrofit.Builder()...build().create(ApiService::class.java)
}
}
// 2. Annotate entry points (Android classes)
@HiltAndroidApp
class MyApp : Application()
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
// Hilt automatically injects UserViewModel
private val viewModel: UserViewModel by viewModels()
}
// 3. Inject into ViewModel
@HiltViewModel
class UserViewModel @Inject constructor(
private val userRepository: UserRepository // Hilt provides this
) : ViewModel() {
// ...
}
Benefits of DI Frameworks
-
Automates Wiring
No manual new UserRepository(new ApiService(...)) chains. Framework builds the graph.
-
Scoping
Manage object lifetimes:
@Singleton (app-wide)
@ActivityScoped / @FragmentScoped (Android lifecycle-aware)
@ViewModelScoped (tied to ViewModel)
-
Testability
Replace modules in test components (Hilt) or override bindings (Koin) to inject mocks.
-
Decoupling
Classes only declare dependencies (constructor params/fields). No knowledge of construction.
-
Compile-Time Safety (Dagger/Hilt)
Errors caught at compile time (vs. runtime crashes with manual DI or Koin).
-
Reduces Boilerplate
Especially with Hilt’s Android-specific integrations.
-
Modularization Support
Easier multi-module projects (Hilt can aggregate modules).
When to Use a DI Framework
- Complex apps with many dependencies.
- Requires scoping (different lifetimes).
- Multi-module projects.
- Testing needs (swap implementations easily).
When to Avoid
- Very small apps (manual DI might suffice).
- Simple prototypes (over-engineering risk).
Key Takeaway
DI frameworks like Hilt/Koin solve the boilerplate and complexity of manual DI by:
- Automating dependency graph construction.
- Integrating with Android lifecycles.
- Enforcing best practices (scoping, single-source-of-truth for dependencies).
They make loose coupling practical at scale, especially in Android apps with Activities, Fragments, ViewModels, and repositories.