访问程序中的DB上下文



有没有办法访问program.cs文件中.NET Core应用程序的DB上下文?我基本上是要使用存储在数据库中的特定选项配置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);
                    });
                });

诀窍是关于如何在单顿中创建范围的服务:


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

尝试执行以下操作:

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

以下代码为.net 6

using (var scope = app.Services.CreateScope())
{
    var service = scope.ServiceProvider;
    var context = service.GetService<MyAppDbContext>();
}

使用此功能,您不仅可以使用DBContext,还可以使用任何其他服务。考虑以下示例的身份类别的usermanager对象:

var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();

我想出了如何做到这一点。您需要手动构建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();
                    });
                });

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

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

和代码注册您的 dbContext in startup.cs 是如下

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

用于构建deb上下文和 program.cs

builder.Services.AddDbContext<StudentDbContext>(option =>
    option.UseSqlServer(builder.Configuration.GetConnectionString("DBCS")));

[1]连接字符串 -
a)&quot" connectionsrings":{{&quot" db; quot":&quot = sql Server名称;数据库=数据库的名称;trusted_connection = true; Trust Server证书= true&quot;}

最新更新