Home > Back-end >  Get Configuration value from IHostBuilder in Net 6
Get Configuration value from IHostBuilder in Net 6

Time:12-08

I am creating a Worker application using Net 6 and I have in Program.cs:

IHostBuilder builder = Host.CreateDefaultBuilder(args);

builder.ConfigureHostConfiguration(x => {
  x.AddJsonFile("settings.json", false, true);
  x.AddJsonFile($"settings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", false, true);
  x.AddEnvironmentVariables();
});

builder.UseSerilog(new LoggerBuilder(
  new LoggerOptions {
    ConnectionString = builder.Configuration.Get<Options>().ConnectionString
  }, 
).CreateLogger());

In LoggerOptions I need to get Options and the ConnectionString from it.

I tried the following because that is what I do when using WebApplicationBuilder:

builder.Configuration.Get<Options>().ConnectionString

But this does not compile as it seems IHostBuilder does not have a Configuration property.

How can I do this?

CodePudding user response:

You can use the following code snippet to get Connection Strings:

builder.Configuration.GetConnectionString("DefaultConnection")

Here is the sample appsettings.json

{
  "ConnectionStrings": {
      "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=MyDB;Integrated Security=True"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

CodePudding user response:

You can access it by using the configure services overload that accepts the HostBuilderContext. I don't typically use the LoggerBuilder:

IHost host = Host.CreateDefaultBuilder(args)
    .UseSerilog((context, loggerConfiguration) =>
    {
        loggerConfiguration.ReadFrom.Configuration(context.Configuration);
    })
    .Build();

await host.RunAsync();
  • Related