MVVM + DI in WPF (C#)
Since you have a lot of C#/.NET experience, I'll show a full, realistic flow in a typical WPF application.
Project structure
MyApp/
├── Models/
│ └── User.cs
├── Services/
│ ├── IUserService.cs
│ └── UserService.cs
├── ViewModels/
│ ├── ViewModelBase.cs
│ └── UserProfileViewModel.cs
├── Views/
│ └── UserProfileView.xaml
├── App.xaml.cs
1. Model
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
2. Service (abstraction + implementation)
public interface IUserService
{
Task<User> GetUserAsync(string id);
}
public class UserService : IUserService
{
private readonly HttpClient _httpClient;
public UserService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<User> GetUserAsync(string id)
{
var response = await _httpClient.GetFromJsonAsync<User>($"api/users/{id}");
return response;
}
}
3. ViewModelBase (INotifyPropertyChanged)
This is the foundation of every ViewModel in WPF - it implements the mechanism that notifies the View about changes.
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return;
field = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
4. ViewModel with injected dependencies
public class UserProfileViewModel : ViewModelBase
{
private readonly IUserService _userService;
private readonly ILogger<UserProfileViewModel> _logger;
private User _user;
public User User
{
get => _user;
set => SetProperty(ref _user, value);
}
private bool _isLoading;
public bool IsLoading
{
get => _isLoading;
set => SetProperty(ref _isLoading, value);
}
public ICommand LoadUserCommand { get; }
// Dependencies come from outside through the constructor - this is the heart of DI
public UserProfileViewModel(IUserService userService, ILogger<UserProfileViewModel> logger)
{
_userService = userService;
_logger = logger;
LoadUserCommand = new RelayCommand(async () => await LoadUserAsync());
}
private async Task LoadUserAsync()
{
try
{
IsLoading = true;
_logger.LogInformation("Loading user...");
User = await _userService.GetUserAsync("123");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to load user");
}
finally
{
IsLoading = false;
}
}
}
Note: the ViewModel knows nothing about HttpClient, the API URL, or how login works - it receives ready, configured dependencies through the constructor. This is exactly constructor injection, the most popular form of DI in .NET.
5. RelayCommand (a simple ICommand implementation)
WPF has no good built-in ICommand, so almost every project has its own RelayCommand:
public class RelayCommand : ICommand
{
private readonly Func<Task> _execute;
private readonly Func<bool> _canExecute;
public RelayCommand(Func<Task> execute, Func<bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute?.Invoke() ?? true;
public async void Execute(object parameter) => await _execute();
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
6. Configuring the DI container in App.xaml.cs
This is where the whole puzzle comes together - Microsoft.Extensions.DependencyInjection (the same one you know from ASP.NET Core) works great in WPF too.
public partial class App : Application
{
private ServiceProvider _serviceProvider;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
// Resolving the main window with its ViewModel
var mainWindow = _serviceProvider.GetRequiredService<MainWindow>();
mainWindow.Show();
}
private void ConfigureServices(IServiceCollection services)
{
services.AddLogging(builder => builder.AddConsole());
services.AddHttpClient<IUserService, UserService>(client =>
{
client.BaseAddress = new Uri("https://api.myapp.pl/");
});
// ViewModel as Transient - a new instance on every resolve
services.AddTransient<UserProfileViewModel>();
// View - MainWindow can also get the ViewModel through its constructor
services.AddSingleton<MainWindow>();
}
protected override void OnExit(ExitEventArgs e)
{
_serviceProvider?.Dispose();
base.OnExit(e);
}
}
7. Injecting the ViewModel into the View
public partial class MainWindow : Window
{
public MainWindow(UserProfileViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel; // View "obserwuje" ViewModel przez binding
}
}
And in XAML:
<Window x:Class="MyApp.Views.MainWindow" ...>
<StackPanel>
<TextBlock Text="{Binding User.Name}" />
<Button Content="Load" Command="{Binding LoadUserCommand}" />
<ProgressBar IsIndeterminate="{Binding IsLoading}" Visibility="{Binding IsLoading, Converter={StaticResource BoolToVisibility}}" />
</StackPanel>
</Window>
Why this approach pays off
- Unit tests of the ViewModel without WPF at all - you swap
IUserServicefor a mock (e.g. Moq) and test theLoadUserAsynclogic without launching a window or a real API. - Easy swapping of implementations - in integration tests you can register
FakeUserServiceinstead of real HTTP. - Lifetime management - the container itself decides whether a dependency is
Singleton,ScopedorTransient, instead of manualnewscattered across the code. - A readable composition of the application in one place (
ConfigureServices) - you see at a glance what the whole app is made of.
Popular DI libraries for WPF
- Microsoft.Extensions.DependencyInjection - the lightest, the same as in ASP.NET Core (I used it above)
- Prism - a full MVVM framework for WPF, with built-in DI + navigation + regions
- CommunityToolkit.Mvvm - a lightweight toolkit from Microsoft with generators for
ObservablePropertyandRelayCommand(less boilerplate than manualSetProperty/RelayCommand)
An example of a full WPF/MVVM application - SimpleTrader
If you want to see these patterns (MVVM, DI, ViewModelBase, RelayCommand, navigation between views) applied in a complete, realistic application - not in an isolated snippet of code - it's worth looking at the SimpleTrader project by SingletonSean:
Repository: github.com/SingletonSean/SimpleTrader Video playlist (step by step): YouTube - SingletonSean
It is a full WPF "trading" application (a simulated stock exchange), built from scratch, episode by episode, covering exactly the topics we discussed:
- MVVM from the ground up -
ViewModelBase,INotifyPropertyChanged,RelayCommand - Dependency Injection - a hand-written DI container of its own (without
Microsoft.Extensions.DependencyInjection), which is educationally valuable - you see how a DI container works "under the hood" before you start using a ready-made one - Navigation between views in WPF without
Frame/NavigationService(WPF doesn't have it natively, unlike e.g. UWP) - a customNavigationStore+NavigationService - The service layer - communication with the backend (authentication, account data) over HTTP
- The Store pattern - shared application state (e.g. the logged-in user) available to many ViewModels at once
Why it's worth it: most MVVM tutorials show a single screen with one button - SimpleTrader shows how these patterns scale in an application with many views, a login screen, navigation and real communication with a backend, which is closer to what you'll meet at work.
Microsoft.Extensions.DependencyInjection, as I showed in the example above.