Dependency Injection in Android with Kotlin: Manual DI, Constructor Injection & Hilt Fundamentals

Dependency Injection (DI) is one of the most important architectural concepts for building scalable, maintainable, and testable Android applications.

As Android projects grow, classes depend on other classes to perform their responsibilities.

For example, a ViewModel may depend on a repository, a repository may depend on a Retrofit API service, and the API service may depend on an OkHttp client.

But who should create these dependencies?

Should every class create its own objects?

How can we replace real dependencies with fake implementations during testing?

How can we share expensive resources such as databases and network clients?

These are some of the problems Dependency Injection helps solve.

In this tutorial, we’ll explore Dependency Injection using Kotlin, Jetpack Compose, ViewModel, and Hilt fundamentals.

We’ll also build a practical User Profile application using manual Dependency Injection.


What You’ll Learn

By the end of this tutorial, you’ll understand:

  • What Dependency Injection is
  • Why Dependency Injection matters
  • Tight coupling vs loose coupling
  • Dependency Inversion Principle
  • Constructor Injection
  • Property Injection
  • Method Injection
  • Manual Dependency Injection
  • Dependency Containers
  • Dependency lifetimes
  • Interface-based dependencies
  • Dependency Injection vs Service Locator
  • Hilt fundamentals
  • Hilt annotations
  • ViewModel injection
  • Repository injection
  • Testing with fake dependencies
  • Production best practices

1. What Is Dependency Injection?

Dependency Injection is a design technique where an object receives the dependencies it needs from an external source rather than creating them internally.

Consider a ViewModel that needs a repository.

Without Dependency Injection

class UserViewModel : ViewModel() {

    private val repository = UserRepositoryImpl()

    fun loadUser() {
        repository.getUser()
    }
}

The ViewModel creates its own repository.

This introduces tight coupling.

The ViewModel is directly responsible for constructing its dependency.

With Dependency Injection

class UserViewModel(
    private val repository: UserRepository
) : ViewModel() {

    fun loadUser() {
        repository.getUser()
    }
}

Now the repository is provided through the constructor.

The ViewModel does not need to know how the repository is created.

This is Dependency Injection.


2. Why Is Dependency Injection Important?

Consider a production Android application with the following components:

Jetpack Compose UI
        |
        v
    UserViewModel
        |
        v
    UserRepository
        |
        v
    Retrofit API
        |
        v
    OkHttp Client

Each component depends on another component.

Without a consistent dependency management strategy, object creation can become complicated.

Benefits of Dependency Injection

  • Reduced coupling
  • Easier unit testing
  • Better separation of concerns
  • Centralized dependency construction
  • Improved maintainability
  • Easier replacement of implementations
  • Clearer object lifetimes
  • Better scalability

Important

Dependency Injection does not automatically guarantee good architecture.

It is a technique that helps organize object creation and dependency ownership.


3. Understanding Tight Coupling

Tight coupling occurs when a class depends directly on a specific implementation.

Example

class NotificationManager {

    private val emailService = EmailService()

    fun sendNotification() {
        emailService.sendEmail()
    }
}

Problem

NotificationManager creates EmailService directly.

Replacing email notifications with push notifications requires modifying NotificationManager.

Testing may also become difficult if EmailService performs real network operations.


4. Understanding Loose Coupling

Loose coupling means components depend on stable contracts rather than unnecessary implementation details.

Example

interface NotificationService {

    fun sendNotification()
}

Email Implementation

class EmailNotificationService : NotificationService {

    override fun sendNotification() {
        println("Email notification sent")
    }
}

Push Implementation

class PushNotificationService : NotificationService {

    override fun sendNotification() {
        println("Push notification sent")
    }
}

Consumer

class NotificationManager(
    private val service: NotificationService
) {

    fun notifyUser() {
        service.sendNotification()
    }
}

Explanation

NotificationManager depends on the NotificationService contract.

Different implementations can be supplied without changing the consumer.


5. Dependency Inversion Principle

The Dependency Inversion Principle (DIP) is one of the SOLID design principles.

It encourages high-level components to depend on abstractions rather than concrete low-level implementations.

Without Dependency Inversion

UserViewModel
     |
     v
RoomUserRepository

The ViewModel depends directly on a specific repository implementation.

With Dependency Inversion

       UserViewModel
             |
             v
       UserRepository
             ^
             |
      RoomUserRepository

Kotlin Example

interface UserRepository {

    suspend fun getUsername(): String
}
class RoomUserRepository : UserRepository {

    override suspend fun getUsername(): String {
        return "Android Developer"
    }
}
class UserViewModel(
    private val repository: UserRepository
) : ViewModel()

Important

Dependency Injection and Dependency Inversion are related but different.

Dependency Injection describes how dependencies are supplied.

Dependency Inversion describes how architectural dependencies should be organized.


6. Types of Dependency Injection

There are three commonly discussed injection techniques.

Constructor Injection

Dependencies are provided through a constructor.

class UserRepository(
    private val apiService: ApiService
)

Constructor Injection is generally preferred because dependencies are explicit and available when the object is created.

Property Injection

Dependencies are assigned to properties.

class AnalyticsManager {

    lateinit var analyticsService: AnalyticsService
}

Property Injection can be useful when a framework creates an object and constructor injection is unavailable.

However, it can introduce partially initialized objects.

Method Injection

Dependencies are passed into individual methods.

class ReportGenerator {

    fun generate(
        formatter: ReportFormatter
    ) {
        formatter.format()
    }
}

Method Injection is useful when a dependency is needed only for a particular operation.


7. Why Constructor Injection Is Preferred

Constructor Injection provides several advantages.

Example

class ProductRepository(
    private val api: ProductApi,
    private val database: ProductDatabase
)

The class cannot be created without its required dependencies.

Benefits

  • Explicit dependencies
  • Easier testing
  • Better immutability
  • Reduced initialization errors
  • Clear object construction

Best Practice

Prefer constructor injection for ordinary Kotlin classes.

Use framework-supported field injection only when necessary.


8. What Is Manual Dependency Injection?

Manual Dependency Injection means developers create and connect dependencies themselves without using a dedicated DI framework.

Example

val api = ProductApiImpl()

val repository = ProductRepositoryImpl(api)

val viewModel = ProductViewModel(repository)

Explanation

Dependencies are created outside their consumers.

Each component receives what it needs.

Advantages

  • No DI framework required
  • Easy to understand
  • Full control over object creation
  • Suitable for small applications
  • Useful for learning DI fundamentals

Limitations

  • More setup code
  • Complex dependency graphs become harder to maintain
  • Scope management requires additional care
  • Boilerplate grows with application complexity

9. What Is a Dependency Container?

A dependency container is a component responsible for creating and holding shared dependencies.

Example

class AppContainer {

    private val api = UserApiImpl()

    val userRepository: UserRepository =
        UserRepositoryImpl(api)
}

Explanation

AppContainer centralizes dependency construction.

Other application components receive dependencies from the container.

Benefits

  • Shared object management
  • Centralized configuration
  • Clear dependency ownership
  • Easier replacement of implementations

Important

Avoid turning the container into a globally accessible object that every class queries directly.

Prefer passing dependencies to consumers explicitly.


10. Understanding Dependency Lifetimes

Different objects require different lifetimes.

Common Lifetimes

Application Lifetime

Suitable for shared resources such as Room databases and configured network clients.

Activity Lifetime

Suitable for dependencies associated with a particular Activity.

ViewModel Lifetime

Suitable for screen-level state holders and their owned resources.

Operation Lifetime

Suitable for short-lived objects used during individual operations.

Example

Application
   |
   +-- AppContainer
   |      |
   |      +-- Retrofit
   |      +-- Room Database
   |      +-- Repository
   |
   +-- MainActivity
          |
          +-- UserViewModel

Best Practice

Choose dependency lifetimes based on ownership, resource usage, and concurrency requirements.

Do not retain Activity references inside application-scoped objects.


Practical Mini-Project: User Profile App with Manual Dependency Injection

Now let’s build a simple User Profile application using Kotlin, Jetpack Compose, ViewModel, StateFlow, and manual Dependency Injection.

Features

  • Display user profile information
  • Load user data through a repository
  • Update the displayed username
  • Manage UI state using StateFlow
  • Inject dependencies through constructors
  • Centralize object creation
  • Test with fake repositories

Technology Stack

  • Kotlin
  • Jetpack Compose
  • Material 3
  • ViewModel
  • StateFlow
  • Coroutines
  • Manual Dependency Injection
  • MVVM

This example uses an in-memory repository to focus on Dependency Injection.


11. Recommended Project Structure

com.example.manualdi/
│
├── MyApplication.kt
├── MainActivity.kt
│
├── di/
│   └── AppContainer.kt
│
├── domain/
│   ├── model/
│   │   └── User.kt
│   └── repository/
│       └── UserRepository.kt
│
├── data/
│   └── InMemoryUserRepository.kt
│
└── presentation/
    ├── UserUiState.kt
    ├── UserViewModel.kt
    ├── UserViewModelFactory.kt
    └── UserProfileScreen.kt

12. Step 1 — Create the User Model

File: domain/model/User.kt

package com.example.manualdi.domain.model

data class User(
    val id: Int,
    val name: String,
    val email: String
)

Explanation

The User model represents the application data.

It does not depend on Android framework classes.


13. Step 2 — Create the Repository Interface

File: domain/repository/UserRepository.kt

package com.example.manualdi.domain.repository

import com.example.manualdi.domain.model.User
import kotlinx.coroutines.flow.Flow

interface UserRepository {

    fun observeUser(): Flow<User>

    suspend fun updateUsername(name: String)
}

Explanation

The repository contract defines operations for observing and updating a user.

The ViewModel will depend on this interface rather than a concrete implementation.


14. Step 3 — Implement the Repository

File: data/InMemoryUserRepository.kt

package com.example.manualdi.data

import com.example.manualdi.domain.model.User
import com.example.manualdi.domain.repository.UserRepository

import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.update

class InMemoryUserRepository : UserRepository {

    private val userState = MutableStateFlow(
        User(
            id = 1,
            name = "Android Developer",
            email = "developer@example.com"
        )
    )

    override fun observeUser(): Flow<User> {
        return userState
    }

    override suspend fun updateUsername(name: String) {

        val updatedName = name.trim()

        if (updatedName.isBlank()) {
            return
        }

        userState.update { currentUser ->
            currentUser.copy(name = updatedName)
        }
    }
}

Explanation

The repository stores the current user in MutableStateFlow.

Whenever the username changes, the repository emits updated data.

Important

This implementation is not persistent.

Data will be lost when the application process terminates.

Use Room or DataStore when durable storage is required.


15. Step 4 — Create the Application Container

File: di/AppContainer.kt

package com.example.manualdi.di

import com.example.manualdi.data.InMemoryUserRepository
import com.example.manualdi.domain.repository.UserRepository

class AppContainer {

    val userRepository: UserRepository =
        InMemoryUserRepository()
}

Explanation

AppContainer creates the repository and owns its lifetime.

The repository can be shared across different application components.


16. Step 5 — Create the Application Class

File: MyApplication.kt

package com.example.manualdi

import android.app.Application
import com.example.manualdi.di.AppContainer

class MyApplication : Application() {

    lateinit var container: AppContainer
        private set

    override fun onCreate() {
        super.onCreate()

        container = AppContainer()
    }
}

Explanation

The Application class creates the dependency container once per application process.

AndroidManifest Configuration

Register the custom Application class.

<application
    android:name=".MyApplication"
    ... >
</application>

The ellipsis represents your existing application attributes.

Keep the remaining manifest configuration generated by Android Studio.


17. Step 6 — Create the UI State

File: presentation/UserUiState.kt

package com.example.manualdi.presentation

import com.example.manualdi.domain.model.User

data class UserUiState(
    val user: User? = null,
    val isLoading: Boolean = true,
    val errorMessage: String? = null
)

Explanation

The UI state represents the information required to render the User Profile screen.


18. Step 7 — Create the ViewModel

File: presentation/UserViewModel.kt

package com.example.manualdi.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope

import com.example.manualdi.domain.repository.UserRepository

import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

class UserViewModel(
    private val repository: UserRepository
) : ViewModel() {

    val uiState: StateFlow<UserUiState> =
        repository.observeUser()
            .map { user ->
                UserUiState(
                    user = user,
                    isLoading = false
                )
            }
            .catch { exception ->
                emit(
                    UserUiState(
                        isLoading = false,
                        errorMessage = "Unable to load profile"
                    )
                )
            }
            .stateIn(
                scope = viewModelScope,
                started = SharingStarted.WhileSubscribed(5_000),
                initialValue = UserUiState()
            )

    fun updateUsername(name: String) {

        viewModelScope.launch {
            repository.updateUsername(name)
        }
    }
}

Explanation

The ViewModel receives UserRepository through constructor injection.

It does not create the repository.

The repository Flow is transformed into UI state.

StateFlow exposes the latest profile state to Jetpack Compose.

Production Note

For a real application, handle update failures explicitly and preserve coroutine cancellation.

Also consider using a separate editable draft state for complex forms.


19. Step 8 — Create the ViewModel Factory

File: presentation/UserViewModelFactory.kt

package com.example.manualdi.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

import com.example.manualdi.domain.repository.UserRepository

class UserViewModelFactory(
    private val repository: UserRepository
) : ViewModelProvider.Factory {

    override fun <T : ViewModel> create(
        modelClass: Class<T>
    ): T {

        if (
            modelClass.isAssignableFrom(
                UserViewModel::class.java
            )
        ) {

            @Suppress("UNCHECKED_CAST")
            return UserViewModel(repository) as T
        }

        throw IllegalArgumentException(
            "Unknown ViewModel class"
        )
    }
}

Explanation

The factory creates UserViewModel with its required repository.

This is a practical example of manual constructor injection.


20. Step 9 — Create the Jetpack Compose Screen

File: presentation/UserProfileScreen.kt

package com.example.manualdi.presentation

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp

import androidx.lifecycle.compose.collectAsStateWithLifecycle

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UserProfileScreen(
    viewModel: UserViewModel
) {

    val uiState by viewModel.uiState
        .collectAsStateWithLifecycle()

    var username by rememberSaveable {
        mutableStateOf("")
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text("Manual DI Profile")
                }
            )
        }
    ) { paddingValues ->

        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .padding(16.dp),
            verticalArrangement =
                Arrangement.spacedBy(16.dp)
        ) {

            when {

                uiState.isLoading -> {

                    CircularProgressIndicator()
                }

                uiState.errorMessage != null -> {

                    Text(
                        text = uiState.errorMessage.orEmpty(),
                        color = MaterialTheme.colorScheme.error
                    )
                }

                uiState.user != null -> {

                    val user = uiState.user!!

                    Text(
                        text = "User Profile",
                        style = MaterialTheme.typography.headlineSmall
                    )

                    Text(
                        text = "Name: ${user.name}"
                    )

                    Text(
                        text = "Email: ${user.email}"
                    )

                    HorizontalDivider()

                    OutlinedTextField(
                        value = username,
                        onValueChange = {
                            username = it
                        },
                        label = {
                            Text("New Username")
                        },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true
                    )

                    Button(
                        onClick = {
                            viewModel.updateUsername(username)
                            username = ""
                        },
                        enabled = username.isNotBlank(),
                        modifier = Modifier.fillMaxWidth()
                    ) {

                        Text("Update Username")
                    }
                }
            }
        }
    }
}

Explanation

The screen observes ViewModel state.

It forwards update requests to the ViewModel.

The screen does not construct the repository or perform data access directly.


21. Step 10 — Create MainActivity

File: MainActivity.kt

package com.example.manualdi

import android.os.Bundle

import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent

import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.remember

import androidx.lifecycle.viewmodel.compose.viewModel

import com.example.manualdi.presentation.UserProfileScreen
import com.example.manualdi.presentation.UserViewModel
import com.example.manualdi.presentation.UserViewModelFactory

class MainActivity : ComponentActivity() {

    override fun onCreate(
        savedInstanceState: Bundle?
    ) {

        super.onCreate(savedInstanceState)

        val app = application as MyApplication

        setContent {

            MaterialTheme {

                val factory = remember {
                    UserViewModelFactory(
                        repository = app.container.userRepository
                    )
                }

                val userViewModel: UserViewModel =
                    viewModel(factory = factory)

                UserProfileScreen(
                    viewModel = userViewModel
                )
            }
        }
    }
}

Explanation

MainActivity retrieves the repository from the application container.

The ViewModel factory injects the repository into UserViewModel.

The ViewModel then exposes UI state to Jetpack Compose.

Complete Dependency Flow

MyApplication
      |
      v
AppContainer
      |
      v
InMemoryUserRepository
      |
      v
UserViewModelFactory
      |
      v
UserViewModel
      |
      v
UserProfileScreen

This demonstrates manual Dependency Injection in a real Android application.


22. Required Dependencies

Create a Kotlin Android project with Jetpack Compose enabled.

Ensure the following dependencies are available.

dependencies {

    implementation(
        "androidx.activity:activity-compose:<version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-viewmodel-ktx:<version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-viewmodel-compose:<version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-runtime-compose:<version>"
    )

    implementation(
        "org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>"
    )

    implementation(
        "androidx.compose.material3:material3"
    )
}

Replace version placeholders with compatible stable versions.

Use the Compose BOM where appropriate.


23. Expected Application UI

Initial Profile Screen

+--------------------------------+
|        Manual DI Profile       |
|                                |
| User Profile                   |
|                                |
| Name: Android Developer        |
|                                |
| Email: developer@example.com   |
|                                |
| ------------------------------ |
|                                |
| [ New Username               ] |
|                                |
|       [ Update Username ]      |
|                                |
+--------------------------------+

After Updating Username

+--------------------------------+
|        Manual DI Profile       |
|                                |
| User Profile                   |
|                                |
| Name: Kotlin Expert            |
|                                |
| Email: developer@example.com   |
|                                |
| ------------------------------ |
|                                |
| [ New Username               ] |
|                                |
|       [ Update Username ]      |
|                                |
+--------------------------------+

Explanation

When the username changes:

  1. The UI calls the ViewModel.
  2. The ViewModel calls the repository.
  3. The repository updates StateFlow.
  4. The ViewModel receives the updated user.
  5. Jetpack Compose renders the new username.

24. What Is Hilt in Android?

Hilt is a Dependency Injection library built on top of Dagger.

It provides standardized dependency management for Android components.

Hilt reduces much of the manual setup required for larger dependency graphs.

Without Hilt

Developers manually create:

  • Application containers
  • Dependency factories
  • ViewModel factories
  • Shared dependency instances
  • Dependency wiring

With Hilt

Hilt generates dependency management code based on annotations and configuration.

Benefits

  • Less manual dependency wiring
  • Android lifecycle integration
  • Constructor injection
  • Component scopes
  • ViewModel integration
  • Easier dependency replacement in tests
  • Compile-time dependency graph validation

25. Important Hilt Annotations

AnnotationPurpose
@HiltAndroidAppInitializes Hilt application integration
@AndroidEntryPointEnables injection into supported Android classes
@InjectRequests constructor or field injection
@HiltViewModelIntegrates ViewModel creation with Hilt
@ModuleDeclares dependency bindings
@InstallInSpecifies the Hilt component
@ProvidesProvides dependencies through a function
@BindsBinds an implementation to an abstraction
@SingletonScopes an instance to the singleton component
@ApplicationContextQualifies an application Context dependency

26. Hilt Application Setup

Create a custom Application class.

@HiltAndroidApp
class MyApplication : Application()

Register it in AndroidManifest.xml.

<application
    android:name=".MyApplication"
    ... >
</application>

Explanation

@HiltAndroidApp enables Hilt’s generated application-level dependency container.

Important

Hilt requires appropriate Gradle plugin, annotation processing, and runtime dependency configuration.

Use the current compatible versions recommended by the Android and Dagger documentation.


27. Constructor Injection with Hilt

Hilt supports constructor injection for classes it can construct.

Example

class UserRepositoryImpl @Inject constructor(
    private val apiService: UserApiService
) : UserRepository {

    override suspend fun getUser(): User {
        return apiService.getUser()
    }
}

Explanation

@Inject tells Hilt how to construct UserRepositoryImpl.

Hilt must also know how to provide UserApiService.

Important

Constructor injection alone does not automatically bind UserRepositoryImpl to the UserRepository interface.

An interface binding must be configured when consumers request the interface type.


28. Hilt ViewModel Injection

Hilt integrates with Android ViewModel.

Example

@HiltViewModel
class UserViewModel @Inject constructor(
    private val repository: UserRepository
) : ViewModel() {

    private val _username =
        MutableStateFlow("")

    val username: StateFlow<String> =
        _username.asStateFlow()
}

Explanation

@HiltViewModel enables Hilt-aware ViewModel creation.

The repository is supplied through constructor injection.

Activity Setup

@AndroidEntryPoint
class MainActivity : ComponentActivity() {

    override fun onCreate(
        savedInstanceState: Bundle?
    ) {
        super.onCreate(savedInstanceState)

        setContent {

            val viewModel: UserViewModel = viewModel()

            UserScreen(viewModel)
        }
    }
}

This assumes the repository and all of its dependencies have valid Hilt bindings.


29. Understanding @Provides

Use @Provides when Hilt cannot construct a dependency through constructor injection.

For example, Retrofit requires builder configuration.

Example

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    @Singleton
    fun provideRetrofit(): Retrofit {

        return Retrofit.Builder()
            .baseUrl("https://example.com/")
            .build()
    }
}

Explanation

Hilt uses the provider function to create Retrofit.

Important

A real API integration also requires the appropriate converter, HTTP configuration, and service bindings.


30. Understanding @Binds

Use @Binds to connect an implementation to an interface.

Example

@Module
@InstallIn(SingletonComponent::class)
abstract class RepositoryModule {

    @Binds
    abstract fun bindUserRepository(
        implementation: UserRepositoryImpl
    ): UserRepository
}

Explanation

When a class requests UserRepository, Hilt can provide UserRepositoryImpl.

Best Practice

Prefer @Binds for straightforward interface-to-implementation bindings.

Use @Provides when object creation requires custom logic.


31. Understanding Hilt Scopes

Hilt scopes control how dependency instances are shared within components.

Common Scopes

ScopeLifetime
@SingletonSingletonComponent lifetime
@ActivityRetainedScopedRetained Activity component lifetime
@ViewModelScopedViewModel component lifetime
@ActivityScopedActivity component lifetime
@FragmentScopedFragment component lifetime

Example

@Singleton
class AnalyticsRepository @Inject constructor()

Important

@Singleton means one instance per SingletonComponent, not necessarily one instance across multiple operating-system processes.

Use scopes only when sharing an instance is appropriate.


32. Dependency Injection vs Service Locator

Dependency Injection and Service Locator are related techniques but have different characteristics.

Dependency Injection

class UserViewModel(
    private val repository: UserRepository
)

The dependency is explicitly provided.

Service Locator

class UserViewModel {

    private val repository =
        ServiceLocator.getUserRepository()
}

The class retrieves its dependency from a central registry.

Comparison

Dependency InjectionService Locator
Dependencies are suppliedDependencies are requested
Dependencies are explicitDependencies may be hidden
Constructor contracts are clearGlobal access is possible
Testing is straightforwardTesting may require registry changes

Recommendation

Prefer explicit constructor injection for application classes.

Use centralized containers primarily for constructing and supplying dependencies.


33. Testing with Fake Dependencies

Dependency Injection makes it easier to test components independently.

Fake Repository

class FakeUserRepository : UserRepository {

    private val userState = MutableStateFlow(
        User(
            id = 1,
            name = "Test User",
            email = "test@example.com"
        )
    )

    override fun observeUser(): Flow<User> {
        return userState
    }

    override suspend fun updateUsername(name: String) {

        userState.update {
            it.copy(name = name)
        }
    }
}

Explanation

The fake repository does not require a database or network connection.

It provides controlled data for testing.


34. ViewModel Unit Testing

Example

@Test
fun `updating username updates repository`() = runTest {

    val repository = FakeUserRepository()

    val viewModel = UserViewModel(repository)

    viewModel.updateUsername("Kotlin Developer")

    advanceUntilIdle()

    val user = repository.observeUser().first()

    assertEquals(
        "Kotlin Developer",
        user.name
    )
}

Important

Because UserViewModel uses viewModelScope, configure Dispatchers.Main with a test dispatcher in JVM unit tests.

Use kotlinx-coroutines-test and a suitable MainDispatcherRule.

This ensures ViewModel coroutines run predictably during testing.


35. Common Dependency Injection Mistakes

Mistake 1: Creating Dependencies Inside ViewModels

Prefer constructor injection.

Mistake 2: Using Global Mutable Singletons Everywhere

Use appropriately scoped dependencies and explicit ownership.

Mistake 3: Injecting Concrete Implementations Unnecessarily

Use interfaces when they provide useful architectural boundaries.

Mistake 4: Creating Too Many Interfaces

Do not create abstractions without a meaningful purpose.

Mistake 5: Incorrect Dependency Scopes

Avoid retaining short-lived Android components in long-lived objects.

Mistake 6: Overusing @Singleton

Not every dependency needs application-wide sharing.

Mistake 7: Using Field Injection When Constructor Injection Is Available

Prefer explicit constructor dependencies.

Mistake 8: Ignoring Testing

Use fake dependencies to test ViewModels and business logic.

Mistake 9: Mixing Dependency Construction with Business Logic

Keep dependency creation separate from application behavior.

Mistake 10: Introducing Hilt Too Early Without Understanding DI

Learn constructor injection and dependency ownership first.


36. Production Best Practices

Follow these recommendations:

  • Prefer constructor injection.
  • Depend on abstractions where useful.
  • Keep dependency construction centralized.
  • Choose appropriate dependency lifetimes.
  • Avoid unnecessary global state.
  • Use application Context only when appropriate.
  • Avoid leaking Activities or Fragments.
  • Keep ViewModels independent of dependency construction.
  • Use @Binds for simple interface bindings.
  • Use @Provides for custom dependency creation.
  • Scope expensive shared resources appropriately.
  • Test components using fake dependencies.
  • Avoid unnecessary DI abstractions.
  • Use Hilt when the dependency graph justifies it.
  • Keep dependency boundaries consistent with your architecture.

37. Dependency Injection Quick Reference

ConceptPurpose
Dependency InjectionSupply dependencies externally
Constructor InjectionInject through constructor
Property InjectionAssign dependencies to properties
Method InjectionSupply dependencies to methods
Dependency InversionDepend on abstractions
Manual DIManually construct dependencies
Dependency ContainerCentralize object creation
HiltAndroid DI framework
DaggerCompile-time DI framework
@InjectConstructor or field injection
@HiltAndroidAppApplication-level Hilt setup
@AndroidEntryPointAndroid component integration
@HiltViewModelHilt ViewModel integration
@ModuleDependency binding definitions
@ProvidesCustom dependency creation
@BindsInterface implementation binding
@SingletonSingletonComponent scope
Fake RepositoryTest implementation

38. Practical Exercises

Exercise 1: Constructor Injection

Create a Logger interface and inject it into a class.

Exercise 2: Interface-Based Dependencies

Implement EmailNotificationService and PushNotificationService.

Exercise 3: Manual Dependency Injection

Create a repository and inject it into a ViewModel.

Exercise 4: Dependency Container

Create an AppContainer that manages shared dependencies.

Exercise 5: User Profile Application

Build the complete User Profile mini-project.

Exercise 6: Fake Repository

Replace the real repository with a fake implementation.

Exercise 7: ViewModel Testing

Test ViewModel behavior using a fake repository.

Exercise 8: Hilt Application

Configure @HiltAndroidApp in a sample project.

Exercise 9: Hilt ViewModel

Create a ViewModel using @HiltViewModel and constructor injection.

Exercise 10: Repository Binding

Use @Binds to connect a repository implementation to its interface.


39. Frequently Asked Questions

What is Dependency Injection in Android?

Dependency Injection is a technique where classes receive required dependencies externally rather than constructing them internally.

Why use Dependency Injection?

It reduces coupling, improves testability, and centralizes dependency management.

What is Constructor Injection?

Constructor Injection provides dependencies through a class constructor.

What is Manual Dependency Injection?

Manual DI means developers create and connect dependencies without a dedicated DI framework.

What is Hilt?

Hilt is a Dependency Injection library built on Dagger that provides standardized Android integration.

Is Hilt required for Android development?

No.

Manual DI is suitable for many applications, particularly smaller projects.

What is the difference between Hilt and Dagger?

Dagger is a general compile-time Dependency Injection framework.

Hilt builds on Dagger and provides Android-specific components, scopes, and integrations.

What is @Inject?

@Inject identifies constructors or fields that participate in dependency injection.

What is @Binds?

@Binds connects an implementation to an interface.

What is @Provides?

@Provides defines how to create a dependency through a provider function.

Does Hilt automatically create every dependency?

No.

Hilt requires valid bindings for every requested dependency in its graph.

Can Dependency Injection improve testing?

Yes.

It allows real dependencies to be replaced with controlled fake implementations.


What We’ve Learned

In this tutorial, we explored:

  • Dependency Injection fundamentals
  • Tight coupling and loose coupling
  • Dependency Inversion Principle
  • Constructor Injection
  • Property and Method Injection
  • Manual Dependency Injection
  • Dependency Containers
  • Dependency lifetimes
  • Interface-based architecture
  • Practical User Profile application
  • ViewModel constructor injection
  • Hilt fundamentals
  • Important Hilt annotations
  • @Provides and @Binds
  • Hilt scopes
  • Dependency Injection vs Service Locator
  • Testing with fake dependencies
  • Production best practices

Dependency Injection is an important foundation for maintainable Android applications.

By combining Kotlin, Jetpack Compose, ViewModel, StateFlow, repositories, and clear dependency ownership, developers can create applications that are easier to extend and test.

The most important principle is simple:

Classes should receive their dependencies instead of unnecessarily creating them.


What’s Next?

In our next tutorial:

Article 44 — Hilt Dependency Injection in Android with Jetpack Compose: Complete Setup & MVVM Integration

You’ll learn:

  • Hilt Gradle configuration
  • @HiltAndroidApp
  • @AndroidEntryPoint
  • @Inject constructor
  • @HiltViewModel
  • @Module and @InstallIn
  • @Provides and @Binds
  • Hilt scopes
  • Retrofit injection
  • Room Database injection
  • Repository injection
  • Navigation Compose integration
  • Hilt testing
  • Practical production-style Android mini-project

Happy Coding!

Continue learning modern Android development with Moiks Developer Blog.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment