簡體   English   中英

ASP.NET CORE EF 中的輔助數據庫上下文

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM