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?
Asked
Active
Viewed 518 times
0
-
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 Answers
-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
-
Will this automatically call Dispose on DBContext on call of RemoveValue()? – Pritam Jun 17 '16 at 08:32
-
Accidentally voted down. Could you please edit the answer so that I can remove it? – smoksnes Jun 19 '16 at 08:43