MVVM Toolkit Dependency Injection

MVVM Toolkit Dependency Injection

Teaches an AI agent to wire CommunityToolkit.Mvvm ViewModels into Microsoft dependency injection: host setup, service lifetimes, messenger registration, resolving ViewModels and testing seams across XAML frameworks.

Skill files2 files

references/

SKILL.md290 lines
1
---
2
name: mvvm-toolkit-di
3
description: 'Wire CommunityToolkit.Mvvm ViewModels into Microsoft.Extensions.DependencyInjection. Covers the .NET Generic Host composition root, constructor injection, service lifetimes (Singleton / Transient / Scoped), IMessenger registration, resolving ViewModels in Views, keyed services, testing seams, and the legacy Ioc.Default escape hatch. Use across WPF, WinUI 3, .NET MAUI, Uno, and Avalonia.'
4
---
5
6
# CommunityToolkit.Mvvm + `Microsoft.Extensions.DependencyInjection`
7
8
The MVVM Toolkit deliberately ships **no DI container** — it composes with
9
`Microsoft.Extensions.DependencyInjection`, the same container ASP.NET
10
Core, Worker services, and the .NET Generic Host use.
11
12
> **TL;DR.** Build the service provider once at startup (prefer
13
> `Host.CreateDefaultBuilder()`). Register services and ViewModels.
14
> Inject through constructors. Avoid `Ioc.Default.GetService<T>()`
15
> in user code.
16
17
---
18
19
## When to use this skill
20
21
- Standing up the composition root for a new XAML app (WPF, WinUI 3,
22
MAUI, Uno, Avalonia)
23
- Choosing service/VM lifetimes
24
- Wiring `IMessenger` once and injecting it into `ObservableRecipient`
25
ViewModels
26
- Resolving a page's ViewModel without coupling to a service locator
27
- Diagnosing "Unable to resolve service for type X while attempting to
28
activate Y"
29
30
For source generators and ViewModel patterns see the **`mvvm-toolkit`**
31
skill. For Messenger pub/sub see **`mvvm-toolkit-messenger`**.
32
33
---
34
35
## Recommended composition root (Generic Host)
36
37
```csharp
38
using Microsoft.Extensions.DependencyInjection;
39
using Microsoft.Extensions.Hosting;
40
using CommunityToolkit.Mvvm.Messaging;
41
42
public partial class App : Application
43
{
44
public IHost Host { get; }
45
46
public App()
47
{
48
Host = Microsoft.Extensions.Hosting.Host
49
.CreateDefaultBuilder()
50
.ConfigureServices((_, services) =>
51
{
52
services.AddSingleton<IFilesService, FilesService>();
53
services.AddSingleton<ISettingsService, SettingsService>();
54
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
55
56
services.AddSingleton<ShellViewModel>();
57
services.AddTransient<ContactViewModel>();
58
services.AddTransient<EditorViewModel>();
59
})
60
.Build();
61
}
62
63
public static T GetService<T>() where T : class =>
64
((App)Current).Host.Services.GetRequiredService<T>();
65
}
66
```
67
68
Generic Host benefits:
69
70
- `appsettings.json` binding via `Microsoft.Extensions.Configuration`
71
- Logging via `Microsoft.Extensions.Logging`
72
- Hosted services (`IHostedService`) for background work
73
- Scope validation in development builds
74
75
> WPF and Windows Forms must integrate the host lifetime with the app
76
> lifetime — see
77
> [Use the .NET Generic Host in a WPF app](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/how-to-use-host-builder).
78
79
### Without Generic Host
80
81
When you only need a service container and want zero extra dependencies:
82
83
```csharp
84
var services = new ServiceCollection();
85
services.AddSingleton<IFilesService, FilesService>();
86
services.AddTransient<ContactViewModel>();
87
ServiceProvider provider = services.BuildServiceProvider();
88
```
89
90
---
91
92
## Constructor injection
93
94
Inject services and child ViewModels through the constructor:
95
96
```csharp
97
public sealed partial class ContactViewModel(
98
IFilesService files,
99
IMessenger messenger,
100
ILogger<ContactViewModel> logger)
101
: ObservableRecipient(messenger)
102
{
103
[ObservableProperty]
104
private string? name;
105
106
[RelayCommand]
107
private async Task SaveAsync()
108
{
109
logger.LogInformation("Saving {Name}", Name);
110
await files.SaveAsync(Name!);
111
}
112
}
113
```
114
115
Why constructor injection beats a service locator:
116
117
- Dependencies are explicit and visible at the call site
118
- Unit tests inject fakes/mocks directly
119
- The DI container validates the dependency graph at startup
120
- Missing registrations throw immediately, not at first use
121
122
---
123
124
## Lifetimes
125
126
| Lifetime | Method | Typical use in XAML apps |
127
|----------|--------|--------------------------|
128
| Singleton | `AddSingleton<T>` | Shell/main-window VM, settings, file/HTTP services, the shared `IMessenger`, app-wide caches |
129
| Transient | `AddTransient<T>` | Per-page or per-document ViewModels (a fresh instance every resolve) |
130
| Scoped | `AddScoped<T>` | Rarely needed in client apps; useful with explicit `IServiceScope` (e.g., per-window scopes) |
131
132
```csharp
133
services.AddSingleton<ShellViewModel>(); // 1 instance for app lifetime
134
services.AddTransient<NoteViewModel>(); // new instance per resolve
135
services.AddScoped<DialogService>(); // 1 per scope (rare)
136
```
137
138
---
139
140
## Resolving in a View
141
142
Resolve the page's root ViewModel in code-behind, then let it pull its
143
own dependencies:
144
145
```csharp
146
public sealed partial class ContactPage : Page
147
{
148
public ContactViewModel ViewModel { get; }
149
150
public ContactPage()
151
{
152
ViewModel = App.GetService<ContactViewModel>();
153
InitializeComponent();
154
}
155
}
156
```
157
158
Bind in XAML with `{x:Bind ViewModel.Xxx}` (compiled bindings) or
159
`{Binding Xxx}` against `DataContext`.
160
161
For navigation frameworks (WinUI 3 `Frame.Navigate`, MAUI Shell, Prism,
162
MVVMCross), let the framework resolve the page and the page resolves its
163
ViewModel from DI. Don't `new` ViewModels manually.
164
165
---
166
167
## `IMessenger` registration
168
169
Register the messenger you want once, inject `IMessenger` everywhere:
170
171
```csharp
172
services.AddSingleton<IMessenger>(WeakReferenceMessenger.Default);
173
// or
174
services.AddSingleton<IMessenger>(StrongReferenceMessenger.Default);
175
```
176
177
Then:
178
179
```csharp
180
public sealed partial class MyViewModel(IMessenger messenger)
181
: ObservableRecipient(messenger) { }
182
```
183
184
For per-window messengers, register with keyed services or as scoped
185
instances and inject into per-window ViewModels.
186
187
See the **`mvvm-toolkit-messenger`** skill for the messenger surface area.
188
189
---
190
191
## Keyed services (.NET 8+)
192
193
Resolve different implementations of the same interface by key:
194
195
```csharp
196
services.AddKeyedSingleton<IExporter, CsvExporter>("csv");
197
services.AddKeyedSingleton<IExporter, JsonExporter>("json");
198
199
public sealed partial class ExportViewModel(
200
[FromKeyedServices("csv")] IExporter csvExporter,
201
[FromKeyedServices("json")] IExporter jsonExporter)
202
: ObservableObject { /* ... */ }
203
```
204
205
---
206
207
## Testing seams
208
209
Constructor-injected dependencies are trivial to swap in tests. With
210
`Moq`:
211
212
```csharp
213
[Fact]
214
public async Task Save_calls_files_service()
215
{
216
var files = new Mock<IFilesService>();
217
var messenger = new WeakReferenceMessenger();
218
var logger = NullLogger<ContactViewModel>.Instance;
219
220
var vm = new ContactViewModel(files.Object, messenger, logger)
221
{
222
Name = "Ada"
223
};
224
225
await vm.SaveCommand.ExecuteAsync(null);
226
227
files.Verify(f => f.SaveAsync("Ada"), Times.Once);
228
}
229
```
230
231
If you're mocking `Ioc.Default` or static state, the ViewModel is using a
232
service locator — refactor to constructor injection.
233
234
---
235
236
## Legacy: `Ioc.Default`
237
238
`CommunityToolkit.Mvvm.DependencyInjection.Ioc` is an escape hatch for
239
cases where constructor injection is impossible — XAML-instantiated VMs
240
for design-time data, `ValueConverter`s, control templates.
241
242
```csharp
243
Ioc.Default.ConfigureServices(
244
new ServiceCollection()
245
.AddSingleton<IFilesService, FilesService>()
246
.AddTransient<ContactViewModel>()
247
.BuildServiceProvider());
248
249
var files = Ioc.Default.GetRequiredService<IFilesService>();
250
```
251
252
Treat it as the last resort. Inside ViewModels, services, and any class
253
the DI container can construct, prefer constructor injection.
254
255
---
256
257
## Common pitfalls
258
259
1. **`Ioc.Default.GetService<T>()` inside a VM constructor.** Hides the
260
dependency, breaks unit tests, prevents startup graph validation.
261
2. **Everything `Singleton`.** A "per-document" VM registered as singleton
262
becomes shared state across all documents — subtle data corruption.
263
Use `AddTransient` for per-instance VMs.
264
3. **Multiple `BuildServiceProvider()` calls.** Each call is a fresh
265
container — singletons aren't shared. Build once at startup.
266
4. **Capturing `IServiceProvider` in long-lived objects.** Indicates a
267
service-locator pattern. Inject the specific dependencies you need.
268
5. **No scope validation in development.** Use `Host.CreateDefaultBuilder()`
269
(which sets `ValidateScopes` and `ValidateOnBuild` in development) so
270
registration mistakes fail at startup, not at first use.
271
6. **Resolving scoped services from the root provider.** They're
272
effectively promoted to singleton lifetime — the warning is silent
273
without scope validation. Either change the lifetime or resolve from
274
an explicit `IServiceScope`.
275
276
---
277
278
## References
279
280
| Topic | File |
281
|-------|------|
282
| Full deep dive (Generic Host setup, lifetimes, keyed services, testing patterns, legacy Ioc) | [`references/dependency-injection.md`](references/dependency-injection.md) |
283
284
External:
285
286
- DI overview: <https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection>
287
- DI usage: <https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage>
288
- MVVM Toolkit Ioc page: <https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/ioc>
289
- Generic Host: <https://learn.microsoft.com/en-us/dotnet/core/extensions/generic-host>
290

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 14,621 prompts

More by @OpenSourceBuffGuy

See all
Sea turtle carrying floating film studio island prompt image

Sea turtle carrying floating film studio island

Draws a giant sea turtle carrying a floating island film studio through a starry sky, where fairies polish rough film strips into golden film.

image-prompt, nano-banana, 3d-render, cartoon, fantasy-world, creatures, animals, whimsical, dreamy, cinematic, dramatic-lighting, vibrant-colors, bokeh, miniature, widescreen, night-scene, illustration, concept-art, surreal, storytelling, clay-3d

Desert buggy escapes drones past industrial outpost prompt image

Desert buggy escapes drones past industrial outpost

Builds a 15-second desert chase video where a racer in an armored buggy escapes drones past an industrial outpost, using five reference images with set jobs.

video-prompt, hailuo, action, multi-shot, timed-beats, camera-movement, reference-image, character-consistency, negative-prompt, cinematic, sci-fi, cars, landscape, aerial-view, tracking-shot, photorealistic, sound-effects, structured-output, long-form, widescreen

1 view
Cozy Pixel Art Farm Island Village prompt image

Cozy Pixel Art Farm Island Village

Draws a cozy 16-bit pixel-art farming village across six small islands joined by bridges, with exact counts for buildings, animals and crops.

image-prompt, gpt-image, pixel-art, isometric, game-assets, concept-art, maps, worldbuilding, cozy, vibrant-colors, ocean, landscape, wide-shot, widescreen, game-development, video-games, structured-output, whimsical, summer, high-angle, aerial-view, animals, negative-prompt, cityscape

1 view

Reviews

Loading reviews…

Discussion

Loading comments…