Tags : Umbraco

Using Autofac in Umbraco 4

Tags : Umbraco

There is a quirk you need to be aware of when trying to set up Autofac (IoC) on WebForms when using Umbraco.  Because Autofac’s WebForms integration tries to inject dependencies into any public property on a masterpage/page/usercontrol, you can see some funky behaviour in the backoffice.  This is because when Autofac sees a public property like:

    public partial class MyUserControl : System.Web.UI.UserControl

    {

        public List<object> MyObjects { get; set; }

it will try to inject and empty list.  In certain places in the backoffice, these public properties are set early in the lifecycle and then overwritten by Autofac.  For example, when you go to create a property on a document type, the list of Data Types will be empty – most unnerving.

The fix is to use explicit injection via attributes – any masterpages/pages/usercontrols which are to have their properties injected need a specific attribute, and the Autofac configuration in the Web.config needs to be tweaked (see above link).  As a result, the above usercontrol examples becomes:

    [InjectProperties]

    public partial class MyUserControl : System.Web.UI.UserControl

    {

        public List<object> MyObjects { get; set; }

and you’re laughing!