configuring-avalonia-dependency-injection

6.6 Dependency Injection and GenericHost Usage

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "configuring-avalonia-dependency-injection" with this command: npx skills add christian289/dotnet-with-claudecode/christian289-dotnet-with-claudecode-configuring-avalonia-dependency-injection

6.6 Dependency Injection and GenericHost Usage

Apply the same GenericHost pattern in AvaloniaUI as in WPF

Project Structure

The templates folder contains a .NET 9 AvaloniaUI project example.

templates/ ├── AvaloniaDISample.App/ ← Avalonia Application Project │ ├── Views/ │ │ ├── MainWindow.axaml │ │ └── MainWindow.axaml.cs │ ├── App.axaml │ ├── App.axaml.cs │ ├── Program.cs │ ├── GlobalUsings.cs │ └── AvaloniaDISample.App.csproj └── AvaloniaDISample.ViewModels/ ← ViewModel Class Library (UI framework independent) ├── MainViewModel.cs ├── GlobalUsings.cs └── AvaloniaDISample.ViewModels.csproj

App.axaml.cs Example:

// 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()
{
    // 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>();

            // Register Views
            services.AddSingleton<MainWindow>();
        })
        .Build();

    if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
    {
        desktop.MainWindow = _host.Services.GetRequiredService<MainWindow>();
    }

    base.OnFrameworkInitializationCompleted();
}

}

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Coding

converting-html-css-to-wpf-xaml

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

managing-styles-resourcedictionary

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

using-xaml-property-element-syntax

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

designing-avalonia-customcontrol-architecture

No summary provided by upstream source.

Repository SourceNeeds Review