簡體   English   中英

處理工作單元

[英]Dispose for Unit Of Work

我有一個代碼,其中控制器調用服務,並且服務使用工作單元來處理DB。 我已經將Unity用作依賴項注入。 請求范圍結束后,我需要自動處理unity(dbContext)。 我沒有在UnityCofig.cs中引用PerRequestLifetimeManager。 有指針嗎?

嘗試創建新的派生類型的生命周期管理器

public class PerHttpRequestLifetime : LifetimeManager
{
    // This is very important part and the reason why I believe mentioned
    // PerCallContext implementation is wrong.
    private readonly Guid _key = Guid.NewGuid();

    public override object GetValue()
    {
        return HttpContext.Current.Items[_key];
    }

    public override void SetValue(object newValue)
    {
        HttpContext.Current.Items[_key] = newValue;
    }

    public override void RemoveValue()
    {
        var obj = GetValue();
        HttpContext.Current.Items.Remove(obj);
    }
}

來源: MVC,EF-Unity中的DataContext單例實例Per-Web-Request

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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