我正在尝试通过依赖注入来访问dbContext。而且有效。
我正在启动时添加dbcontext
Services.AddDbContextPool<ApplicationDbContext>(options =>
{
options.UseMySql(Configuration["ConnectionStrings:DefaultConnection"],
b => b.MigrationsAssembly("Persistence"));
options.UseOpenIddict();
});
我也在中介中添加所有请求处理程序
services.AddMediatR(typeof(ChangePasswordRequestHandler).GetTypeInfo().Assembly);
我正在调解器的另一个请求中调用一个请求。这是一个示例
public class CreateComment : IRequestHandler<CreateCommentRequestModel, ResponseViewModel>
{
private readonly ApplicationDbContext _context;
private readonly IMediator _mediator;
public CreateComment(ApplicationDbContext context, IMediator mediator)
{
_context = context;
_mediator = mediator;
}
public async Task<ResponseViewModel> Handle(CreateCommentRequestModel request, CancellationToken cancellationToken)
{
_ = _mediator.Send(new SendCommentNotificationRequestModel(), CancellationToken.None);
return new ResponseViewModel();
}
这里是另一个请求处理程序
public class SendCommentNotification : IRequestHandler<SendCommentNotificationRequestModel, ResponseViewModel>
{
private readonly ApplicationDbContext _context;
private readonly IMediator _mediator;
public SendCommentNotification(ApplicationDbContext context, IMediator mediator)
{
_context = context;
_mediator = mediator;
}
public async Task<ResponseViewModel> Handle(SendCommentNotificationRequestModel request, CancellationToken cancellationToken)
{
await _mediator.Send(new SendNotificationToManyRequestModel(), CancellationToken.None);
return new ResponseViewModel();
}
}
这是我的第三个处理程序
public class SendNotificationToMany : IRequestHandler<SendNotificationToManyRequestModel, ResponseViewModel>
{
private readonly ApplicationDbContext _context;
private readonly INotificationService _notificationService;
public SendNotificationToMany(
INotificationService notificationService, ApplicationDbContext context)
{
_notificationService = notificationService;
_context = context;
}
public async Task<ResponseViewModel> Handle(SendNotificationToManyRequestModel request,
CancellationToken cancellationToken)
{
//DbContext is disposed hence not usable when accessed here.
return new ResponseViewModel();
}
}
问题是在第三个Handler上工作时DbContext被处置了。我该怎么解决?
如果在第一个处理程序上添加await
,则它应能正常工作,但我不想等待,我希望它在后台运行。
我知道修复程序很小,但是我无法弄清楚。
Kestrel在请求的生存期内创建一个服务范围。合并范围完成后,将处理所有IDisposable
服务。
我认为错误位于此处: