Using Unity.MVC5 and Unity.WebAPI in Umbraco

If you have ever tried to configure an Umbraco application to use Unity.WebAPI and Unity.MVC5 then you may well have experienced the error 'An error occurred when trying to create a controller of type LegacyTreeController'. This post explains the reason for the error and reveals the single line of code that is necessary to fix it.

There is already a blog post dealing with using Unity.MVC5 and Unity.WebAPI in the same project but this will not be enough to get Umbraco working 100%. Your own controllers should all function correctly but if you run the /umbraco admin area and try navigating, you will soon come across the following:

Failed to retrieve data for child nodes undefined

An error occurred when trying to create a controller of type 'LegacyTreeController'. Make sure that the controller has a parameterless public constructor.

The error message is not hugely helpful. If we look up LegacyTreeController, it does have a parameterless public constructor but for reasons outlined below, it is not being called by Unity when resolving the controller.

When it comes to resolving components, Unity takes a greedy approach, preferring that largest constructor when there are multiple. If we take a look at LegacyTreeController, we find two constructors - a parameterless one and a complicated one which we want to stay away from.

public class LegacyTreeController : TreeControllerBase
{
    public LegacyTreeController();
    public LegacyTreeController(XmlTreeNode xmlTreeNode, string treeAlias, string currentSection, UrlHelper urlHelper);
}

If the default convention does not work (as is the case here), it is very easy to tell Unity which constructor we want to use. All we need is an additional registration (in UnityConfig.cs by default):

container.RegisterType<LegacyTreeController>(new InjectionConstructor());

Restart the application and everything should work once again and you can now inject dependencies into all your SurfaceControllers, UmbracoApiControllers and RenderMvcControllers in the same way as a regular ASP.NET application.

Comments

Be the first person to comment on this article.