xiaohongshu
xiaohongshu
configuring-dependency-injection
Configures Dependency Injection using Microsoft.Extensions.DependencyInjection and GenericHost. Use when setting up DI container, registering services, or implementing IoC patterns in .NET projects.
Full skill instructions
A guide on using Dependency Injection and GenericHost in .NET projects.
// 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)
{
await _emailService.SendWelcomeEmailAsync(user.Email);
}
}
}
// App.xaml.cs
namespace MyApp;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public partial class App : Application
{
private readonly IHost _host;
public App()
{
// Create GenericHost and register services
_host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
// Register services
services.AddSingleton<IUserRepository, UserRepository>();
services.AddSingleton<IUserService, UserService>();
services.AddTransient<IDialogService, DialogService>();
// Register ViewModels
services.AddTransient<MainViewModel>();
services.AddTransient<SettingsViewModel>();
// Register Views
services.AddSingleton<MainWindow>();
})
.Build();
}
protected override async void OnStartup(StartupEventArgs e)
{
await _host.StartAsync();
// Get MainWindow from ServiceProvider
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
protected override async void OnExit(ExitEventArgs e)
{
using (_host)
{
await _host.StopAsync();
}
base.OnExit(e);
}
}
// MainWindow.xaml.cs
namespace MyApp;
using System.Windows;
public partial class MainWindow : Window
{
// ViewModel injection through Constructor Injection
public MainWindow(MainViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
}
// ViewModels/MainViewModel.cs
namespace MyApp.ViewModels;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
public sealed partial class MainViewModel : ObservableObject
{
private readonly IUserService _userService;
private readonly IDialogService _dialogService;
// Constructor Injection
public MainViewModel(IUserService userService, IDialogService dialogService)
{
_userService = userService;
_dialogService = dialogService;
LoadDataAsync();
}
[ObservableProperty] private ObservableCollection<User> _users = [];
[RelayCommand]
private async Task LoadDataAsync()
{
try
{
var userList = await _userService.GetAllUsersAsync();
Users = new ObservableCollection<User>(userList);
}
catch (Exception ex)
{
await _dialogService.ShowErrorAsync("Error occurred", ex.Message);
}
}
}
Creates only one instance throughout the application
services.AddSingleton<IUserRepository, UserRepository>()Creates one instance per request (Scope)
services.AddScoped<IUserService, UserService>()Creates a new instance on every request
services.AddTransient<MainViewModel>()// Service Locator pattern (anti-pattern)
public sealed class SomeClass
{
private readonly IServiceProvider _serviceProvider;
public SomeClass(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void DoSomething()
{
// ⚠️ Not recommended: Using ServiceProvider directly
var service = _serviceProvider.GetRequiredService<IUserService>();
}
}
// Correct way: Use Constructor Injection
public sealed class SomeClass
{
private readonly IUserService _userService;
public SomeClass(IUserService userService)
{
_userService = userService;
}
public void DoSomething()
{
// ✅ Recommended: Use service injected through Constructor Injection
_userService.GetAllUsersAsync();
}
}
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
</ItemGroup>
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience