c# - 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);
});
});
解决方案
诀窍是关于如何在单例中创建作用域服务:</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
}
});
}
推荐阅读
- angular - 角度错误:“mat-form-field”不是已知元素”
- spring - 如何使用数据源动态初始化 QueryDSL SQL 模板
- javascript - 如何用textarea更改段落
- c - 如何在链表中正确执行弹出功能?
- elasticsearch - 如何在elasticsearch中索引和查询字典数据类型?
- docker - 如何检查状态已退出的 docker 容器的内容 (1)
- python - 使用 tfidf.vectorizer 后如何获取每个类的单词的最高 tf-idf 值
- node.js - 对返回承诺的 hapijs(v20) 处理程序的并发请求
- c++ - 我可以使用模板参数作为变量吗?
- javascript - 节点将pdf从快速文件上传转换为文本