100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
.NET

Dependency Injection in MVVM

How MVVM ViewModels receive their collaborators — data services, navigation, dialogs — via constructor injection instead of creating them directly, and why that makes apps testable and swappable.

ArchitectureIntermediate9 min readJul 10, 2026
Analogies

Dependency Injection in MVVM

Dependency Injection (DI) is the practice of supplying a class's collaborators from the outside rather than having the class construct them itself. In MVVM, a ViewModel that needs data access, navigation, or dialog services declares those needs as interface parameters in its constructor — for example IOrderService or INavigationService — instead of calling 'new OrderService()' internally. This inversion of control means the ViewModel depends only on abstractions, so the concrete implementation (a REST client today, a cached local store tomorrow) can change without touching ViewModel code, and the ViewModel becomes trivially testable in isolation.

🏏

Cricket analogy: It's like a captain who is handed a bowler by the team management rather than picking a random net bowler himself — Rohit Sharma trusts the panel's choice of Bumrah for the death overs, and can request a different bowler for a different pitch without rewriting his game plan.

Constructor Injection vs. Service Locator

Constructor injection — passing every dependency as a constructor parameter — is the preferred DI style in MVVM because it makes a ViewModel's requirements explicit and impossible to forget: the compiler refuses to build the object without them. The Service Locator pattern, where a ViewModel pulls dependencies from a global 'ServiceLocator.Get<IFoo>()' call at runtime, looks convenient but hides dependencies inside method bodies, making the class harder to test (you must configure a global registry before every test) and easier to misuse (nothing stops a developer from requesting a service the ViewModel was never designed to need). Most production MVVM codebases standardize on constructor injection and reserve service location, if at all, for framework glue code at the composition root.

🏏

Cricket analogy: It's the difference between a scorecard that lists every player required before the match starts (constructor injection) versus a substitute being fetched from the pavilion mid-over whenever someone remembers they're short a fielder (service locator) — the first is auditable, the second invites surprises.

csharp
// Constructor injection: dependencies are explicit and required
public class OrderViewModel : ObservableObject
{
    private readonly IOrderService _orderService;
    private readonly INavigationService _navigationService;

    public OrderViewModel(IOrderService orderService, INavigationService navigationService)
    {
        _orderService = orderService ?? throw new ArgumentNullException(nameof(orderService));
        _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));
    }

    public async Task LoadOrdersAsync()
    {
        Orders = await _orderService.GetOrdersAsync();
    }
}

// Anti-pattern: Service Locator hides the real dependencies
public class OrderViewModelBad
{
    public async Task LoadOrdersAsync()
    {
        var orderService = ServiceLocator.Current.GetInstance<IOrderService>(); // hidden dependency
        Orders = await orderService.GetOrdersAsync();
    }
}

DI Containers and Lifetime Management

A DI container (Microsoft.Extensions.DependencyInjection, Autofac, or Prism's built-in container) centralizes the mapping from interface to implementation and resolves entire object graphs automatically: ask the container for an OrderViewModel and it constructs IOrderService, INavigationService, and anything they in turn depend on. Lifetimes matter — a Singleton like INavigationService should live for the app's lifetime, a Scoped service might live per-page or per-user-session, and a Transient service like a fresh IValidator should be created every time it's requested. Getting lifetimes wrong is a common MVVM bug source: registering a ViewModel as Singleton, for instance, causes stale state to leak across navigations because the same instance is reused instead of a fresh one being created per visit.

🏏

Cricket analogy: It's like an IPL franchise's team management deciding which players are contracted for the full season (Singleton — say, the captain), which are brought in for a specific away leg (Scoped), and which are one-match net bowlers hired fresh each game (Transient) — mixing these up, like keeping an injured player as 'permanent captain,' causes problems.

csharp
// App composition root (e.g., MauiProgram.cs or App.xaml.cs)
var services = new ServiceCollection();

services.AddSingleton<INavigationService, NavigationService>();
services.AddScoped<IUserSessionService, UserSessionService>();
services.AddTransient<IValidator<Order>, OrderValidator>();

services.AddTransient<OrderViewModel>();   // fresh ViewModel per navigation
services.AddTransient<OrderListView>();

var provider = services.BuildServiceProvider();
var orderViewModel = provider.GetRequiredService<OrderViewModel>();

Testing ViewModels with Mocked Dependencies

Because DI-driven ViewModels depend only on interfaces, unit tests can substitute lightweight fakes or mocking-framework doubles (Moq, NSubstitute) for the real services, verifying ViewModel logic without a database, network, or UI. A test can construct 'new OrderViewModel(mockOrderService.Object, mockNavigationService.Object)', configure the mock to return a canned list of orders, call LoadOrdersAsync, and assert the ViewModel's Orders collection and IsLoading flag ended up correct — all in milliseconds, with no I/O. This is the single biggest testability win MVVM plus DI provides over code-behind, where UI logic is entangled with concrete controls and hard to exercise outside a running application.

🏏

Cricket analogy: It's like practicing a run-chase scenario in the nets against a bowling machine set to simulate Jasprit Bumrah's yorkers, rather than only ever testing your technique in a real match against the real bowler — the simulated version is fast, repeatable, and safe to run a hundred times.

csharp
[Fact]
public async Task LoadOrdersAsync_PopulatesOrders_OnSuccess()
{
    var mockOrderService = new Mock<IOrderService>();
    mockOrderService.Setup(s => s.GetOrdersAsync())
        .ReturnsAsync(new List<Order> { new Order { Id = 1, Total = 49.99m } });
    var mockNav = new Mock<INavigationService>();

    var vm = new OrderViewModel(mockOrderService.Object, mockNav.Object);
    await vm.LoadOrdersAsync();

    Assert.Single(vm.Orders);
    Assert.Equal(49.99m, vm.Orders[0].Total);
}

Watch for constructor over-injection: a ViewModel needing eight or more dependencies is usually a sign it has too many responsibilities. Group related services behind a facade (e.g., an ICheckoutContext bundling payment, shipping, and inventory services) or split the ViewModel.

  • DI supplies a ViewModel's collaborators from outside via constructor parameters instead of the ViewModel constructing them itself.
  • Constructor injection makes dependencies explicit and compiler-enforced; Service Locator hides them and is generally an anti-pattern in MVVM.
  • DI containers (Microsoft.Extensions.DependencyInjection, Autofac, Prism) resolve full object graphs and manage service lifetimes.
  • Choosing the wrong lifetime — especially Singleton for something that should be Transient — is a common source of stale-state MVVM bugs.
  • DI enables fast, isolated unit tests by letting mocked implementations of interfaces stand in for real services.
  • A ViewModel needing too many injected dependencies signals it should be split or given a facade service.

Practice what you learned

Was this page helpful?

Topics covered

#NET#MVVMDesignPatternStudyNotes#MicrosoftTechnologies#DependencyInjectionInMVVM#Dependency#Injection#MVVM#Constructor#StudyNotes#SkillVeris