Home > Software engineering >  Inject IConfiguration to windows forms on .NET 6.0
Inject IConfiguration to windows forms on .NET 6.0

Time:03-23

I have class library called Persistence.EFCore contains this method

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

and this is my code from Program.cs in winform project

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);
    }
}

I can't find a way to set the Configuration value.
The Configuration from IConfiguration supposed to get his value from

Configuration = builder.Build();

But in my case the

services.AddPersistenceServices(Configuration);

came before the build

CodePudding user response:

The first parameter of ConfigureService((context, services)=>{ ... }) is HostBuilderContext which gives you access to configuration, using its Configuration property.

So assuming you have a service extension method which accepts configuration, then you can easily pass configuration to it using context.Configuration.

Example

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>();
            });
}
  • Related