Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DB Context in program.cs

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);
                    });
                });
like image 986
Tachyon Avatar asked Apr 24 '26 09:04

Tachyon


2 Answers

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();
like image 138
Anton Toshik Avatar answered Apr 25 '26 23:04

Anton Toshik


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>>();
like image 35
raw_hitt Avatar answered Apr 25 '26 23:04

raw_hitt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!