I have almost always used Unity in my applications but today I’ve had to fix broken code due to a recent installation of Unity in an Umbraco solution. While you can install Unity just like you would on any other ASP.NET application, it turns out that there are some Umbraco controllers/types that you need to specifically register on your UnityConfig for it to work. If you don’t, you will get several problems like the following:
[ResolutionFailedException: Resolution of the dependency failed, type = "Umbraco.Web.Mvc.RenderMvcController", name = "(none)". Exception occurred while: while resolving. Exception is: InvalidOperationException - The type UmbracoContext does not have an accessible constructor.
Umbraco.Web.Editors.SectionController - Unhandled controller exception occurred System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
Here are the steps I took to eventually get Unity to work:
- Install Unity.MVC via Nuget. Tutorial here (see section “ASP.NET MVC with Unity”)
- On your UnityConfig.cs, make sure you have the following registered:
container.RegisterType<UmbracoContext>( new ContainerControlledLifetimeManager(), new InjectionFactory(c => UmbracoContext.Current)) .RegisterType<RenderMvcController>( new InjectionConstructor(new ResolvedParameter<UmbracoContext>())); container.RegisterType<HealthCheckController>(new InjectionConstructor()); container.RegisterType<UserTreeController>(new InjectionConstructor()); container.RegisterType<UsersController>(new InjectionConstructor());
Works on Umbraco 7.7.9 🙂