c# - 在 DependencyInjection 之外创建 DBContext
问题描述
我正在创建一个 ASP.NET Core 应用程序。它使用 Entity Framework Core 进行数据库访问。我在 Startup.cs 中使用 services.AddDbContext 并且数据库上下文按预期注入到我的控制器中。
我还有一个使用 IHostedService 作为单例添加的后台任务。我想在我的 IHostedService 实现中有一个我的 DBContext 实例。当我尝试这样做时,我得到一个运行时错误,我的 IHostedService 无法使用范围服务(我的数据库上下文)。
DB Context 类采用 DbContextOptions 选项的参数并将选项传递给基本构造函数 (DbContext)。
我需要在 IHostedService (单例对象)的实现中创建我的数据库上下文的实例,但我似乎无法弄清楚如何从我的 IHostedService 实现中正确创建 DbContextOptions 的新实例。
解决方案
Scoped Service
要从 a解析 a Singleton Service
,您可以从IServiceProvider
.
这是演示代码:
public class DbHostedService : IHostedService
{
private readonly ILogger _logger;
public DbHostedService(IServiceProvider services,
ILogger<DbHostedService> logger)
{
Services = services;
_logger = logger;
}
public IServiceProvider Services { get; }
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service is starting.");
DoWork();
return Task.CompletedTask;
}
private void DoWork()
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service is working.");
using (var scope = Services.CreateScope())
{
var context =
scope.ServiceProvider
.GetRequiredService<ApplicationDbContext>();
var user = context.Users.LastOrDefault();
_logger.LogInformation(user?.UserName);
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation(
"Consume Scoped Service Hosted Service is stopping.");
return Task.CompletedTask;
}
}
推荐阅读
- python - 将 DataFrame 附加到现有的 google 工作表而不附加标题行
- python - AttributeError:“ResourceSummaryWriter”对象没有属性“add_summary”
- java - 活动崩溃,因为表不存在
- flutter - 如何在两个“ThemeData”类之间进行插值
- javascript - 运行命令 cy.exec('npm run sfdx:latest-leads') 将更改 json 文件格式
- jsf - 如何根据条件使有条件需要的元素不需要
- java - 如何在 Mock 方法中添加属性文件 - Mockito
- node.js - 如何在 MERN 堆栈应用程序中使函数等待状态更新
- java - 打开 Feign java.lang.NoSuchFieldError: MULTIPART_RELATED 错误
- python - 规范化列:总和为 1