0

I have a code where controller calls service and service use Unit Of Work to handle DB. I have used Unity as dependency injection. I need to dispose unity(dbContext) automatically after request scope ends. I am not getting reference to PerRequestLifetimeManager in UnityCofig.cs. Any pointers?

Pritam
  • 939
  • 2
  • 12
  • 36
  • Are you trying to find the PerRequestLifetimeManager, or do you ask for suggestion on how to dispose your UoW? – smoksnes Jun 17 '16 at 06:15
  • Doesn't unity detect if your UoW is disposable and automatically call Dispose when the request is finished? – Neil Jun 17 '16 at 09:16

1 Answers1

-1

Try creating new derived type of lifetime manager

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);
    }
}

Source: MVC, EF - DataContext singleton instance Per-Web-Request in Unity

Community
  • 1
  • 1
JSJ
  • 5,391
  • 3
  • 22
  • 30