Configures Dependency Injection using Microsoft.Extensions.DependencyInjection and GenericHost. Use when setting up DI container, registering services, or implementing IoC patterns in .NET projects.
View on GitHubchristian289/dotnet-with-claudecode
wpf-dev-pack
wpf-dev-pack/skills/configuring-dependency-injection/SKILL.md
January 23, 2026
Select agents to install to:
npx add-skill https://github.com/christian289/dotnet-with-claudecode/blob/main/wpf-dev-pack/skills/configuring-dependency-injection/SKILL.md -a claude-code --skill configuring-dependency-injectionInstallation paths:
.claude/skills/configuring-dependency-injection/# Dependency Injection and GenericHost Usage
A guide on using Dependency Injection and GenericHost in .NET projects.
## Project Structure
The templates folder contains a .NET 9 WPF project example.
```
templates/
├── WpfDISample.App/ ← WPF Application Project
│ ├── Views/
│ │ ├── MainWindow.xaml
│ │ └── MainWindow.xaml.cs
│ ├── App.xaml
│ ├── App.xaml.cs
│ ├── GlobalUsings.cs
│ └── WpfDISample.App.csproj
└── WpfDISample.ViewModels/ ← ViewModel Class Library (UI framework independent)
├── MainViewModel.cs
├── GlobalUsings.cs
└── WpfDISample.ViewModels.csproj
```
## Core Principles
- **Implement dependency injection using Microsoft.Extensions.DependencyInjection**
- **Use GenericHost (Microsoft.Extensions.Hosting) as the default**
- **Apply service injection through Constructor Injection**
## Console and General Projects - Program.cs
```csharp
// Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
// Configure DI using GenericHost
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
// Register services
services.AddSingleton<IUserRepository, UserRepository>();
services.AddScoped<IUserService, UserService>();
services.AddTransient<IEmailService, EmailService>();
// Register main application service
services.AddSingleton<App>();
})
.Build();
// Get service through ServiceProvider
var app = host.Services.GetRequiredService<App>();
await app.RunAsync();
// Application class - Constructor Injection
public sealed class App(IUserService userService, IEmailService emailService)
{
private readonly IUserService _userService = userService;
private readonly IEmailService _emailService = emailService;
public async Task RunAsync()
{
// Use injected services
var users = await _userService.GetAllUsersAsync();
foreach (var user in users)
{