在program.cs中访问数据库上下文

时间:2019-03-07 08:55:02

标签: c# asp.net-core kestrel-http-server

是否有一种方法可以访问program.cs文件中的.NET Core应用程序的数据库上下文?我基本上是希望使用存储在数据库中的特定选项来配置Kestrel,因此我需要访问数据库上下文。

我基本上是在尝试做这样的事情:

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);
                    });
                });

4 个答案:

答案 0 :(得分:1)

诀窍是关于如何在单例内创建范围服务:


    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
                }
            });
    }

答案 1 :(得分:0)

尝试执行以下操作:

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();

答案 2 :(得分:0)

我想出了怎么做的方法。您需要手动为数据库上下文建立配置,然后实例化上下文,然后才能使用它。这是万一有人在这个位置上的代码。

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseSentry()
                .UseKestrel(opts =>
                {
                    opts.Listen(IPAddress.Any, 443, listenOpts =>
                    {
                        //Create the configuration to read from appsettings.json
                        var configuration = new ConfigurationBuilder().AddJsonFile(
                                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json"))
                            .Build();

                        //Create the DB Context options
                        var optionsBuilder = new DbContextOptionsBuilder<DBContext>()
                            .UseSqlServer(configuration["ConnectionString:Development"]);

                        //Create a new database context
                        var context = new DBContext(optionsBuilder.Options);

                        //Get the certificate
                        var certificate = context.Certificates.First();
                    });
                });

答案 3 :(得分:-1)

是的,您可以使用以下代码获取服务

 var host = BuildWebHost(args);

DbContext context = host.Services.GetService<DbContext>();

以及在 startup.cs 中注册 DbContext 的代码如下

services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));