gpt4 book ai didi

c# - DbContext Unity 不调用 HttpContextLifetimeManager.RemoveValue() 坏事?

转载 作者:太空宇宙 更新时间:2023-11-03 16:34:25 25 4
gpt4 key购买 nike

我正在定义我的 DbConntextObj

_container.RegisterType<IDbConntextObj, DbConntextObj>(new HttpContextLifetimeManager<DbConntextObj>());

Unity 没有在 lifetimemanager 上调用 RemoveValue()

我有一个 Dbcontext 用于多个存储库。

我的 lifetimemanager 看起来像这样:

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 Dispose 是件坏事吗?Unity 和 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 实现中。

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

关于c# - DbContext Unity 不调用 HttpContextLifetimeManager.RemoveValue() 坏事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9611541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com