在program.cs中访问DB Context

问题描述 投票:1回答:4

有没有办法在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);
                    });
                });
c# asp.net-core kestrel-http-server
4个回答
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
                }
            });
    }

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

0
投票

我想出了如何去做这件事。您需要手动构建DB上下文的配置,然后实例化上下文,然后您就可以使用它。这是代码,以防任何人处于这个位置。

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

-1
投票

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

 var host = BuildWebHost(args);

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

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

services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
© www.soinside.com 2019 - 2024. All rights reserved.