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?
Simple example:
var hostBuilder = Host.CreateDefaultBuilder(args);
hostBuilder.UseSerilog((hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
});
hostBuilder.ConfigureServices((hostContext, services) =>
{
var connectionString = hostContext.Configuration.GetConnectionString("MyConnectionString");
}
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
I'd like to fetch both App Configuration and KeyVault values directly from IConfiguration. This is from a console application in .Net 7
Program.cs:
var host = Host.CreateDefaultBuilder()
.ConfigureLogging(a => a.AddConsole())
.ConfigureHostConfiguration(config => config.AddEnvironmentVariables())
.ConfigureAppConfiguration(config =>
{
config.ConfigureKeyVault();
})
.ConfigureServices((context, services) =>
{
var env = context.HostingEnvironment;
var startUp = new Startup(env);
startUp.ConfigureServices(services);
startUp.ConfigureConsoleMethods(services);
_serviceProvider = services.BuildServiceProvider(true);
})
.Build();
Extension Method:
public static void ConfigureKeyVault(this IConfigurationBuilder config)
{
var settings = config.Build();
var appConfigConnString = settings.GetConnectionString("AppConfig");
var keyVaultEndpoint = settings.GetValue<string>("KeyVault:Endpoint");
var kvOptions = new DefaultAzureCredentialOptions { ManagedIdentityClientId = settings.GetValue<string>("KeyVault:ClientId") };
config.AddAzureAppConfiguration(options =>
{
options.Connect(appConfigConnString);
options.ConfigureKeyVault(x => x.SetCredential(new DefaultAzureCredential(kvOptions)));
});
}
With this setup, I can fetch my KeyVault keys like this:
services.AddScoped<IApiFactory, ApiFactory>(x =>
{
var keyVault = x.GetRequiredService<IKeyVaultService>();
return new ApiFactory(
keyVault.GetSecret("SomeObj:ClientId"),
keyVault.GetSecret("SomeObj:ClientSecret"));
});
But I would rather get my key's using IConfiguration, like this:
services.AddScoped<IApiFactory, ApiFactory>(x =>
{
return new ApiFactory(
this.Configuration.GetValue<string>("SomeObj:ClientId"),
this.Configuration.GetValue<string>("SomeObj:ClientSecret"));
});
Question
How can I fetch my KeyVault values from IConfiguration?
If you set up a key vault reference in Azure App Configuration, the secret retrieved from the key vault should be accessible from IConfiguration.
Make sure the key name (e.g. "SomeObj:ClientId") is the one that you set in Azure App Configuration instead of the secret name you set in Key Vault.
Make sure the configuration is built before you attempt to access it.
I don't want to use CreateDefaultBuilder and ConfigureWebHostDefaults in Program.cs file. Both of these functions make certain assumptions, that I am not comfortable with, also I don't want to rely on ASP.net defaults. I want to setup builder myself but don't know how to do that
I want to replace following code with my own builder
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(builder =>
{
builder.Sources.Clear();
...
})
.ConfigureWebHostDefaults(webBuilder =>
{
...
})
.ConfigureServices((context, services) =>
services.Configure<...>(
context.Configuration.GetSection("...")))
.Build();
You can create an instance of HostBuilder directly:
var host = new HostBuilder()
.Build();
HostBuilder has a number of useful methods, such as ConfigureServices, ConfigureAppConfiguration, etc:
var host = new HostBuilder()
.ConfigureAppConfiguration(builder =>
{
// ...
})
.ConfigureServices((context, services) =>
{
// ...
})
.Build();
To configure the WebHost, without the defaults, use ConfigureWebHost:
var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
})
.Build();
I've got app in .net core 5.
And this is the code in Startup.cs
'''''
public static IHostBuilder CreateHostBuilder(string[] args) =>
//Host.CreateDefaultBuilder(args)
// .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder
.UseStartup<Startup>()
.UseKestrel(o =>
{
o.Listen(IPAddress.Any, 443, opt =>
{
opt.UseHttps("pathfto.pfx", "passwordtocert");
});
});
});
I would like to take upgrade it to .net core 6
I thought that it would be like this
var builder = WebApplication.CreateBuilder(args);
builder.Host
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseKestrel(o =>
{
o.Listen(IPAddress.Any, 443, opt => { opt.UseHttps("pathto.pfx", "passwordtocert"); });
});
});
But it doesn't work when I try compile it.
Thank you in advance for any solutions.
Try to use builder.WebHost
builder.WebHost.ConfigureKestrel(options =>
{
options.Listen(IPAddress.Any, int.Parse(builder.Configuration.GetSection("SSL")["port"]), listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
if (builder.Configuration.GetSection("SSL")["sertificateName"].Trim() != "")
listenOptions.UseHttps(Path.Combine(AppContext.BaseDirectory, "cfg", builder.Configuration.GetSection("SSL")["sertificateName"]), builder.Configuration.GetSection("SSL")["password"]);
});
});
More details you find on https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0
Your problem is your trying builder.Host instead of builder.WebHost. I think this would be the equivalent.
Program.cs
builder.WebHost.ConfigureKestrel(opt => {
opt.ListenAnyIP(443, listOpt =>
{
listOpt.UseHttps(#"pathto.pfx", "passwordtocert");
});
});
var app = builder.Build();
I'm currently working on console application that should be able to log to both console and database using Serilog and built-in Dependency injection to pass Ilogger via constructor to other services. Im running the latest Net Core.
Now my problem with the code below is that in RobotService I'm trying to log all the levels of logs, but I can only see the logs in console. The autocreated table in database called "Logs" is empty.
I'm not quite sure what am I doing wrong. Have anybody dealt with somethins similar?
Thanks a lot for any input.
public class Program
{
static void Main(string[] args)
{
var host = AppStartup();
var robotService = ActivatorUtilities.CreateInstance<RobotService>(host.Services);
robotService.Run();
static IConfigurationRoot ConfigSetup()
{
return new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
}
static IHost AppStartup()
{
var appSettings = ConfigSetup();
var host = Host.CreateDefaultBuilder()
.UseSerilog()
.ConfigureServices((context, services) =>
{
services.AddTransient<IRobotService, RobotService>();
services.AddTransient<IStrategyService, StrategyService>();
})
.Build();
Serilog.Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.WriteTo.MSSqlServer(
connectionString: appSettings.GetConnectionString("DevConnection"),
sinkOptions: new MSSqlServerSinkOptions
{
TableName = "Logs",
AutoCreateSqlTable = true
},
columnOptions: new ColumnOptions()
).CreateLogger();
return host;
}
}
}
Trying to setup Azure App Configuration with Azure Key Vault in Program.cs and getting following error:
'IConfigurationBuilder' does not contain a definition for
'AddAzureAppConfiguration'
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
var settings = config.Build();
config.AddAzureAppConfiguration(options =>
{
options.Connect(settings["ConnectionStrings:AppConfig"])
.ConfigureKeyVault(kv =>
{
kv.SetCredential(new DefaultAzureCredential());
});
});
})
.UseStartup<Startup>());
adding following package fixed it:
dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore
Or even better:
dotnet add package Microsoft.Extensions.Configuration.AzureAppConfiguration
Clear and simple Microsoft Documentation for the App Config integration.