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

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse