首页 > 解决方案 > 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);
                    });
                });

标签: c#asp.net-corekestrel-http-server

解决方案


诀窍是关于如何在单例中创建作用域服务:</p>


    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

   public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel(opt => {
                var sp = opt.ApplicationServices;
                using(var scope = sp.CreateScope() ){
                    var dbContext=scope.ServiceProvider.GetService<AppDbContext>();
                    var e= dbContext.Certificates.FirstOrDefault();
                    // now you get the certificates
                }
            });
    }

推荐阅读