C#实现依赖注入
in 默认分类 with 0 comment

使用微软官方库 Microsoft.Extensions.DependencyInjection

在WPF中使用

public sealed partial class App : Application
{
    public App()
    {
        Services = ConfigureServices();

        this.InitializeComponent();
    }

    /// <summary>
    /// Gets the current <see cref="App"/> instance in use
    /// </summary>
    public new static App Current => (App)Application.Current;

    /// <summary>
    /// Gets the <see cref="IServiceProvider"/> instance to resolve application services.
    /// </summary>
    public IServiceProvider Services { get; }

    /// <summary>
    /// Configures the services for the application.
    /// </summary>
    private static IServiceProvider ConfigureServices()
    {
        var services = new ServiceCollection();

        services.AddSingleton<IFilesService, FilesService>();
        services.AddSingleton<ISettingsService, SettingsService>();
        services.AddSingleton<IClipboardService, ClipboardService>();
        services.AddSingleton<IShareService, ShareService>();
        services.AddSingleton<IEmailService, EmailService>();

        return services.BuildServiceProvider();
    }
}

主要接口

// 创建服务集合
using Microsoft.Extensions.DependencyInjection;
using System;

// 定义服务接口
public interface IMyService
{
    void DoWork();
}

// 定义服务实现类
public class MyService : IMyService
{
    public void DoWork()
    {
        Console.WriteLine("MyService is working.");
    }
}

class Program
{
    static void Main()
    {
        // 创建服务集合
        IServiceCollection services = new ServiceCollection();

        // 注册服务
        services.AddTransient<IMyService, MyService>();

        // 手动创建 ServiceDescriptor 并注册
        var descriptor = new ServiceDescriptor(typeof(IMyService), typeof(MyService), ServiceLifetime.Transient);
        services.Add(descriptor);

        // 构建服务容器
        IServiceProvider serviceProvider = services.BuildServiceProvider();

        // 解析服务
        IMyService myService = serviceProvider.GetRequiredService<IMyService>();
        myService.DoWork();

        // 尝试解析服务,如果未注册返回 null
        IMyService? nullableService = serviceProvider.GetService<IMyService>();
        if (nullableService != null)
        {
            nullableService.DoWork();
        }
    }
}