Unity.MVC3
Sat Mar 10 2012 by MarkP
As the final part of the upgrade of this site to MVC 3, I decided to change the IoC container from Castle Windsor to Unity. I have been using Unity is many projects recently so decided to use the knowledge gained to replace the container and also utilise the IDependencyResolver interface which replaces the Common Service locator class, which is new in MVC 3.
There is an interesting project on codeplex called Unity.MVC3 which simplifies the process further and also provides a simple way of disposing of objects per HttpRequest using the HierarchicalLifetimeManager(), which is especially useful when using ORMS such as Entity Framework where you need to dispose of the context object, if this is being injected into your classes.
The code now is greatly simplified for my implementation as follows:
- IUnityContainer container = UnityRegistrar.Register();
- DependencyResolver.SetResolver(new UnityDependencyResolver(container));
- public class UnityRegistrar
- {
- public static IUnityContainer Register()
- {
- var container = new UnityContainer();
- container.RegisterType<IMailHandler, SmtpMailHandler>();
- container.RegisterType<IBlogCreator<XContainer>, XmlBlogCreator>();
- container.RegisterType<IResourceRepository, ResourceRepository>();
- container.RegisterType<IUserRepository, UserRepository>();
- container.RegisterControllers();
- return container;
- }
- }
Downloads
Unity.MVC3
Unity IoC Version 2.1


