avalonia-dependency-injection
AvaloniaUI에서 GenericHost와 DI 사용 패턴
When & Why to Use This Skill
This Claude skill provides a standardized implementation pattern for integrating Microsoft GenericHost and Dependency Injection (DI) within AvaloniaUI applications. It enables developers to build scalable, maintainable, and testable cross-platform desktop applications by leveraging modern .NET architectural practices for service lifetime management and ViewModel orchestration.
Use Cases
- Architecting professional-grade AvaloniaUI applications with a clean separation of concerns using the Microsoft.Extensions.DependencyInjection framework.
- Integrating standard .NET ecosystem features such as Logging, Configuration, and Background Services into Avalonia projects via the GenericHost builder.
- Streamlining the MVVM pattern by automating the registration and resolution of ViewModels and Views, facilitating easier unit testing and decoupled development.
| name | avalonia-dependency-injection |
|---|---|
| description | "AvaloniaUI에서 GenericHost와 DI 사용 패턴" |
6.6 Dependency Injection 및 GenericHost 사용
AvaloniaUI에서도 WPF와 동일하게 GenericHost 패턴 적용:
// App.axaml.cs
namespace MyApp;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public partial class App : Application
{
private IHost? _host;
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
// GenericHost 생성 및 서비스 등록
// Create GenericHost and register services
_host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
// Services 등록
// Register services
services.AddSingleton<IUserRepository, UserRepository>();
services.AddSingleton<IUserService, UserService>();
services.AddTransient<IDialogService, DialogService>();
// ViewModels 등록
// Register ViewModels
services.AddTransient<MainViewModel>();
// Views 등록
// Register Views
services.AddSingleton<MainWindow>();
})
.Build();
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow = _host.Services.GetRequiredService<MainWindow>();
}
base.OnFrameworkInitializationCompleted();
}
}