在 .NET 6.0 上将 IConfiguration 注入 windows 表单

Inject IConfiguration to windows forms on .NET 6.0

我有 class 个名为 Persistence.EFCore 的库包含此方法

public static IServiceCollection AddPersistenceServices(this IServiceCollection services, IConfiguration configuration)
{
    services.AddDbContext<SIMContext>(options =>
           options.UseSqlServer(configuration.GetConnectionString("ConnectionString")));
    services.AddTransient<IUnitOfWork, UnitOfWork>();
    return services;
}

这是我在 winform 项目Program.cs中的代码

public static IConfiguration Configuration { get; }
      [STAThread]
      static void Main()
      {
         ApplicationConfiguration.Initialize();
         var builder = new HostBuilder()
         .ConfigureAppConfiguration((hostContext, builder) =>
         {
            builder.AddJsonFile("apsettings.json", optional: true, reloadOnChange: true);
            
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddScoped<XtraMain>();
            services.AddPersistenceServices(Configuration);
            services.AddApplicationServices();
            services.AddTransient<FrmExpressionOfNeeds>();
            services.AddSingleton<IFormFactory, FormFactory>();

        });

    var host = builder.Build();
    using (var serviceScope = host.Services.CreateScope())
    {
        IServiceProvider services = serviceScope.ServiceProvider;
        XtraMain mainform = services.GetRequiredService<XtraMain>();
        System.Windows.Forms.Application.Run(mainform);
    }
}

我找不到设置配置值的方法。
IConfiguration 中的配置应该从

中获取他的值
Configuration = builder.Build();

但就我而言

services.AddPersistenceServices(Configuration);

在构建之前出现

ConfigureService((context, services)=>{ ... }) is HostBuilderContext which gives you access to configuration, using its Configuration的第一个参数属性.

所以假设您有一个接受配置的服务扩展方法,那么您可以使用 context.Configuration.

轻松地将配置传递给它

例子

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
internal static class Program
{
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        var host = CreateHostBuilder().Build();
        Application.Run(host.Services.GetRequiredService<Form1>());
    }
    static IHostBuilder CreateHostBuilder() =>
        Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                services.AddHelloServices(context.Configuration);
                services.AddTransient<Form1>();
            });
}