Most IDependencyResolver implementations using Unity do not work with IDisposable and using them can lead to memory leaks and connection issues. Unity.Mvc3 is an assembly that includes a fuller implementation of IDependencyResolver that uses a child container per web request to ensure that IDisposable instances are disposed of at the end of each request. All of these complexities are taken care of by the assembly and integration into a project is as simple as adding a single line of code.
Background
ASP.NET MVC 3 has a new mechanism for integrating an IoC container into the MVC pipeline. It involves writing an implementation of IDependencyResolver and registering it using the staticDependencyResolver.SetResolver method. It is a trivial process to write a simple DependencyResolver for Unity, but the vast majority of versions that you will see do not handle IDisposable, leading to memory leaks in your applications when dealing with disposable components. Here is a typically naive implementation:
public class OverlySimpleUnityDependencyResolver : IDependencyResolver
{ private readonly IUnityContainer _container;
public OverlySimpleUnityDependencyResolver(IUnityContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
return _container.IsRegistered(serviceType)
? _container.Resolve(serviceType)
: null;
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType);
}
}Whilst this works perfectly well for most types, if you were to register a type that implements IDisposable, you will find that the Dispose method never gets called. If you use an object relational mapper (ORM) such as NHibernate or Entity Framework, failing to dispose of your ISession / ObjectContext / DBContext will leave connections open, resulting in database timeouts and other serious problems. It is therefore imperative to handle IDisposable correctly within your IoC container.
In the vast majority of IoC containers, you can solve this problem relatively easily by registering your IDisposable objects with a lifestyle of per web request. That way, at the end of the request, the container will automatically call dispose for you. It is a shame that Unity does not come with such a lifestyle and whilst you can find many implementations on the Net, most are far too simplistic and do not deal with the IDisposable issue at all.
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();
}