我正在开发一个ASP.Net MVC 3 Web应用程序,它使用Unity 2.0作为它的IoC容器。ASP.Net MVC 3 Unity IoC处置
下面显示了我的的Application_Start的例子()方法在我的Global.asax文件
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IUnityContainer container = new UnityContainer();
container.RegisterType<IControllerActivator, CustomControllerActivator>(
new HttpContextLifetimeManager<IControllerActivator>());
//container.RegisterType<IUnitOfWork, UnitOfWork>(
// new ContainerControlledLifetimeManager());
container.RegisterType<IUnitOfWork, UnitOfWork>(
new HttpContextLifetimeManager<IUnitOfWork>());
container.RegisterType<IListService, ListService>(
new HttpContextLifetimeManager<IListService>());
container.RegisterType<IShiftService, ShiftService>(
new HttpContextLifetimeManager<IShiftService>());
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
我HttpContextLifetimeManager看起来像这样
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
public override object GetValue()
{
return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] =
newValue;
}
public void Dispose()
{
RemoveValue();
}
}
我的问题是,方法Dispose()在上面的类中从来没有调用过,当我把ab关注它。我担心我的IoC容器实例从未被处置。这是否会导致问题?
我发现)这个代码片断,我放在我的的Global.asax文件,但仍的Dispose(方法不会被调用
protected void Application_EndRequest(object sender, EventArgs e)
{
using (DependencyResolver.Current as IDisposable);
}
谁能帮我该如何处置我的Unity容器的每个实例?
谢谢。
的'HierarchicalLifetimeManager'处置与寿命创建的对象,当容器它与设置注册。如果您在每次请求时都这样做,您将失去很多性能。 – 2012-07-26 20:46:38
但我用它很好:)小孩的容器被丢弃。请参阅unity.mvc3软件包详细信息:允许Microsoft Unity Unity IoC容器与ASP.NET MVC 3的简单集成的库。此项目包含一个定制的DependencyResolver,它可以为每个HTTP请求创建一个子容器,并在最后处理所有注册的IDisposable实例的请求。 – 2012-07-27 15:33:29
我之前看过这个项目。使用起来很简单,而且完成这项工作。但我一般不喜欢子容器的概念(尽管这是个人观点)。为每个请求设置Unity的构建管道的性能退化取决于您在子容器中注册的次数以及Web负载应用程序。 – 2012-07-27 17:20:51