![](/img/trans.png)
[英]ASP.NET Core and EF application stops at initialising Database context
[英]Secondary Db Context in ASP.NET CORE EF
我有一个发送通知的服务,它需要一个数据库连接来查找订阅。 我还有一个控制器(可能还有更多)可以执行一些逻辑并发送通知。
问题是,因为DI它使用DbContext
的相同实例,所以我在同一上下文中重新使用DataReader
抛出错误(可以理解)。
我真的很想在不启用DbConnectionString
的 MARS 标志的情况下执行此操作。 鉴于控制器不能使用.ToList()
或没有跟踪并且“内部” NotificationService
需要查找数据库 - 这甚至可能吗?
public class NotificationSystem
{
private readonly DbContext context;
public NotificationSystem(DbContext context) { this.context = context;}
public void SendNotification(string username){
var subscriptions = context.subscriptions.where(u => u.username == username);
// Do some notification stuff
}
}
和一个简单的控制器
public class SendRemindersController : Controller
{
private readonly DbContext _context;
private readonly NotificationSystem _notificationSystem;
public SendRemindersController(DbContext context, NotificationSystem notificationSystem)
{
this._context = context;
this._notificationSystem = notificationSystem;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var reminders = _context.Reminders.Where(r => r.Sent == false && r.RemindAt < DateTime.UtcNow);
foreach (var reminder in reminders)
{
await _notificationSystem.SendNotificationToUser(reminder.UserId);
reminder.Sent = true;
}
await _context.SaveChangesAsync();
return Ok();
}
}
还有startup.cs
(是的,我知道我没有使用过接口,稍后会重构)。
services.AddDbContext<DbContext>(options => options.UseSqlServer(connection));
services.AddTransient<NotificationSystem, NotificationSystem>();
这个问题是有缺陷的,因为我错误地认为 .ToList/.ToArray 也将实体与上下文分离。 事实上,这些不会分离,只会执行查询。
这是因为您使用相同的DbContext
来执行多个并发事务。 如果像这样将.ToListAsync()
添加到这行代码中
var reminders = await _context.Reminders
.Where(r => r.Sent == false && r.RemindAt < DateTime.UtcNow)
.ToListAsync();
它会立即检索所有的提醒,然后循环(这个声明之后)中的代码可以使用DbContext
没有DbContext
抛出异常,因为积极的结果集仍然被遍历。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.