How to access appsettings from Blazor Hybrid in Winforms

199 views Asked by At

I'm trying to setup DI in a Winforms Blazor app. Winforms is used simply a placeholder for the all the Blazor functionality. I understand the Blazor DI is setup within the form constructor (as per Dan Roth sample app):

public partial class Form1 : Form
 {
     public Form1()
     {
         InitializeComponent();

         var services = new ServiceCollection();
         services.AddWindowsFormsBlazorWebView();
         services.AddSingleton<WeatherForecastService>();
         blazorWebView1.HostPage = "wwwroot\\index.html";
         blazorWebView1.Services = services.BuildServiceProvider();
         blazorWebView1.RootComponents.Add<Main>("#app");
     }

 }

instead of the Winforms Program.cs. However, some of the services require configuration from appsettings.json, which I would normally do in the program.cs as:

 var builder = CreateHostBuilder()
     .ConfigureAppConfiguration((context, builder) =>
         {
             builder.AddJsonFile("appsettings.json");
             builder.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json");
         });

 var host = builder.Build();

Similarly, CommectionString also comes from appsettings.

So how do you either access builder.Configuration from the Form (Blazor side)? Or access it as normal in Winforms startup and provide it to the Blazor startup?

 services.AddSingleton<ISheetToolConfig>(
     builder.Configuration.GetSection("SheetToolConfig").Get<SheetToolConfig>()
         ?? throw new NullReferenceException("SheetToolConfig"));
0

There are 0 answers