本文介绍了的DbContext团结不调用HttpContextLifetimeManager.RemoveValue()坏事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我定义我DbConntextObj
I'm defining my DbConntextObj
_container.RegisterType<IDbConntextObj, DbConntextObj>(new HttpContextLifetimeManager<DbConntextObj>());
团结就是不上lifetimemanager调用RemoveValue()
Unity is not calling the RemoveValue() on the lifetimemanager
我有一个的DbContext为多个存储库。
I have one Dbcontext for multiple repositories.
我lifetimemanager看起来是这样的:
My lifetimemanager looks like this:
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
private readonly string _itemName = typeof(T).AssemblyQualifiedName;
public override object GetValue()
{
return HttpContext.Current.Items[_itemName];
}
public override void RemoveValue()
{
var disposable = GetValue() as IDisposable;
HttpContext.Current.Items.Remove(_itemName);
if (disposable != null)
disposable.Dispose();
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[_itemName] = newValue;
}
public void Dispose()
{
RemoveValue();
}
}
这是个坏事的DbContext处置不被叫什么名字?
有一种解决方法对于团结和MVC3?
Is it a bad thing that DbContext Dispose is not being called?Is there a workaround For Unity and MVC3?
推荐答案
试试这个。
public class MvcApplication : HttpApplication
{
private IUnityContainer unityContainer;
private HttpContextDisposableLifetimeManager ContextLifeTimeManager;
/// <summary>
/// The start method of the application.
/// </summary>
protected void Application_Start()
{
unityContainer = new UnityContainer();
ContextLifeTimeManager = new HttpContextDisposableLifetimeManager();
//for some reason this event handler registration doesn't work, meaning we have to add code to
//Application_EndRequest as below...
//this.EndRequest += new EventHandler(ContextLifeTimeManager.DisposingHandler);
unityContainer.RegisterType<IUnitOfWork, EFUnitOfWork>(ContextLifeTimeManager);
unityContainer.RegisterType<IRepository<ShoppingCart>, ShoppingCartRepository>(new ContainerControlledLifetimeManager());
}
//this seems hackish, but it works, so whatever...
protected void Application_EndRequest(Object sender, EventArgs e)
{
if (ContextLifeTimeManager != null)
{
ContextLifeTimeManager.RemoveValue();
}
}
}
然后在你的LifeTimeManager实现。
Then in your LifeTimeManager implementation.
public class HttpContextDisposableLifetimeManager : LifetimeManager, IDisposable
{
const string _itemName = typeof(T).AssemblyQualifiedName;
public void DisposingHandler(object source, EventArgs e)
{
RemoveValue();
}
public override object GetValue()
{
return HttpContext.Current.Items[_itemName];
}
public override void RemoveValue()
{
Dispose();
HttpContext.Current.Items.Remove(_itemName);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[_itemName] = newValue;
}
public void Dispose()
{
var obj = (IDisposable)GetValue();
obj.Dispose();
}
}
这篇关于的DbContext团结不调用HttpContextLifetimeManager.RemoveValue()坏事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!