I usually do the following
static void Main()
{
IConfiguration config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
Host.CreateDefaultBuilder()
.ConfigureServices(isc =>
{
isc.AddSingleton(config);
isc.AddDbContext<DbContext>(options =>
{
options.UseSqlServer(config.GetConnectionString("Duplicate"));
});
})
.Build();
}
I just knew that configuration for appsettings.json is already provided by CreateDefaultBuilder() so I think I should be able to simplify my code as follows.
static void Main()
{
Host.CreateDefaultBuilder()
.ConfigureServices(isc =>
{
isc.AddDbContext<DbContext>(options =>
{
options.UseSqlServer(********.GetConnectionString("Duplicate"));
});
})
.Build();
}
How to obtain the configuration ******** provided by default?
You can access it by using another overload of ConfigureServices:
Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
var config = context.Configuration;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With