I am developing an ASP.Net MVC 3 Web application which uses Unity 2.0 as it's IoC container.
Below shows an example of my Application_Start() method in my Global.asax file
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));
}
My HttpContextLifetimeManager looks like this
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();
}
}
My issue is that, the method Dispose() in the above class is never called when I put a breakpoint on it. I am worried that my IoC container instance is never being disposed of. Could this lead to problems?
I found this snippet of code which I placed in my Global.asax file, but still the Dispose() method never gets called
protected void Application_EndRequest(object sender, EventArgs e)
{
using (DependencyResolver.Current as IDisposable);
}
Can anyone help me with how to dispose of each instance of my Unity container?
Thanks.