Is there a way to access the DB context of a .NET Core application in the program.cs file? I am basically looking to configure Kestrel with specific options that are stored in the database so I would need access to the database context.
I am basically trying to do something like this:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSentry()
.UseKestrel(opts =>
{
opts.Listen(IPAddress.Any, 443, listenOptions =>
{
var storedCert = _db.Certificates.First(c => c.Id == 1);
var certBytes = Convert.FromBase64String(storedCert.CertificatePfx);
var certPassword = storedCert.CertificatePassword;
var cert = new X509Certificate2(certBytes, certPassword);
listenOptions.UseHttps(cert);
});
});
Try to do the following:
var host = CreateWebHostBuilder(args).Build();
var scope = host.Services.CreateScope();
var ctx = scope.ServiceProvider.GetRequiredService<MyDbContext>();
//get a new WebHostBuilder
CreateWebHostBuilder(args)
//Configure here using the ctx
.Build()
.Run();
Well the below code worked for me for .net 6
using (var scope = app.Services.CreateScope())
{
var service = scope.ServiceProvider;
var context = service.GetService<MyAppDbContext>();
}
Using this you can use not only get dbcontext but any other service. Consider below example for usermanager object of identity class:
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
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