How to use Unity in an Umbraco solution

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.

Or this:

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:

  1. Install Unity.MVC via Nuget. Tutorial here (see section “ASP.NET MVC with Unity”)
  2. On your UnityConfig.cs, make sure you have the following registered:
                 new ContainerControlledLifetimeManager(),
                 new InjectionFactory(c => UmbracoContext.Current))
                 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 🙂

Submit your review

Create your own review

Average rating:  
 0 reviews

Add a Comment

Your email address will not be published. Required fields are marked *