Dependency Injection in the MVVM architecture
A quick reminder: what MVVM is
MVVM (Model-View-ViewModel) is an architectural pattern that splits an application into three layers:
- Model - data and business logic (e.g. fetching data from an API, the database)
- View - the UI layer (components, screens) - "dumb", it only displays
- ViewModel - the mediator between Model and View - holds UI state, reacts to user actions, calls the Model
The View "observes" the ViewModel (through binding/reactivity), and the ViewModel knows nothing about the View - this is crucial for testability.
Where does DI fit into all this?
The problem: the ViewModel needs access to the Model (e.g. an API service, a data repository) to do its job. The question is - where does the ViewModel get these dependencies from?
Without DI (bad) - the ViewModel creates its own dependencies
public class UserProfileViewModel
{
private readonly UserApiService _apiService = new UserApiService(); // sztywno wpisana konkretna klasa
private readonly ConsoleLogger _logger = new ConsoleLogger();
public async Task LoadUser(string id)
{
_logger.Log("Loading user...");
var user = await _apiService.GetUser(id);
}
}
This violates the Dependency Inversion Principle we discussed with SOLID - the ViewModel is tightly coupled to the concrete UserApiService implementation. Consequences:
- You can't swap it for a mock in unit tests
- You can't use another data source (e.g. a cache, a different endpoint) without changing the ViewModel's code
- It's hard to manage the lifetime of dependencies (e.g. singleton vs a new instance)
With DI (good) - dependencies are injected from outside
public interface IUserApiService
{
Task<User> GetUser(string id);
}
public interface ILogger
{
void Log(string message);
}
public class UserProfileViewModel
{
private readonly IUserApiService _apiService;
private readonly ILogger _logger;
public UserProfileViewModel(IUserApiService apiService, ILogger logger)
{
_apiService = apiService;
_logger = logger;
}
public async Task LoadUser(string id)
{
_logger.Log("Loading user...");
var user = await _apiService.GetUser(id);
}
}
// Creating the ViewModel - dependencies "injected" from outside
var viewModel = new UserProfileViewModel(
new UserApiService(),
new ConsoleLogger()
);
The ViewModel now depends on abstractions (interfaces), not on concrete classes - exactly the D principle from SOLID.
Why this is especially important in MVVM
- Testing the ViewModel without the UI - this is the main point of MVVM. You can test the ViewModel's logic by injecting mocks instead of real services:
var mockApiService = new Mock<IUserApiService>();
mockApiService.Setup(s => s.GetUser("1")).ReturnsAsync(new User { Id = "1", Name = "Test User" });
var viewModel = new UserProfileViewModel(mockApiService.Object, new NoOpLogger());
await viewModel.LoadUser("1");
mockApiService.Verify(s => s.GetUser("1"), Times.Once);
Without DI you'd have to fire real API requests in tests, or do ugly hacks with swapping modules.
-
Separation of responsibilities - the ViewModel doesn't have to know how to construct its dependencies (e.g. that
UserApiServiceneeds a base URL, an auth token etc.) - that's the job of an external "composer". -
Reusability - the same ViewModel can work with different implementations (e.g.
FakeUserApiServicein offline/demo mode).
The DI container (Dependency Injection Container)
In larger applications, creating and passing dependencies by hand (as above) becomes tedious, so you use a DI container, which automatically creates and injects dependencies based on registrations:
using Microsoft.Extensions.DependencyInjection; // pakiet NuGet z tym samym API co w ASP.NET Core
// 1. Create the service collection - this is the "registry" where you record
// what should be what (interface -> concrete implementation)
var services = new ServiceCollection();
// 2. Rejestracja (raz, przy starcie aplikacji)
services.AddSingleton<ILogger, ConsoleLogger>();
services.AddSingleton<IUserApiService, UserApiService>();
// IMPORTANT: the ViewModel must be registered too, otherwise GetRequiredService
// below will throw "Unable to resolve service" - resolving
// applies to EVERYTHING that is to be created by the container, not just "services"
services.AddTransient<UserProfileViewModel>();
// 3. Zbuduj kontener (IServiceProvider) na podstawie rejestracji z kroku 2 -
// this is the moment the "registry" turns into a working container
var serviceProvider = services.BuildServiceProvider();
// 4. Resolving dependencies (automatic) - the container ITSELF calls the constructor of
// UserProfileViewModel, injecting ILogger and IUserApiService into it
var viewModel = serviceProvider.GetRequiredService<UserProfileViewModel>();
What each step does: ServiceCollection is an empty list of registrations - by itself it can't create anything yet. The Add* methods (AddSingleton, AddTransient, AddScoped) only add an entry "when someone asks for X, give them Y". BuildServiceProvider() compiles these entries into an actual, working container - this is the moment the container checks whether everything can be assembled. GetRequiredService<T>() only then actually creates the instance, calling the constructor and injecting the registered dependencies.
Popular examples in different ecosystems:
- Android (Kotlin/Java): Hilt, Koin, Dagger
- iOS (Swift): Swinject, Resolver
- .NET/WPF: Microsoft.Extensions.DependencyInjection, Autofac
- Angular: built-in DI container
- Frontend TS in general: tsyringe, InversifyJS
Summary in one sentence
DI in MVVM means the ViewModel receives its dependencies (services, repositories) instead of creating them itself - which lets you test it in isolation from the UI and from concrete data implementations, and that is really the whole point of the MVVM pattern.