castle-windsorioc-containerproperty-injection

Windsor Func<T> property injection


Using Windsor 2.5.2, the following works:

public class Foo
{
    public IBar Bar { get; set; }
}

To delay creation of IBar, this also works:

public class Foo
{
    public Foo(Func<IBar> barFactory)
    { 
    }
}

However, if I combine property injection with Func<T>, the following results in a null reference:

public class Foo
{
    public Func<IBar> Bar { get; set; }
}

How can I make Windsor inject the Func<IBar>?


Solution

  • That's a great question Paul. I'm glad you asked.

    For implicitly registered Funcs Windsor is looking at the property, sees it's optional, and it just doesn't bother trying to get it, since... well - it's optional, so you surely are happy not having the dependency populated.

    To have it populated, you either register the factory explicitly

    container.Register(Component.For<Func<IBar>>().AsFactory().Lifestyle.Transient);
    

    or you mark the dependency as required (on ComponentModel using Require method) which is probably best done via an IComponentModelConstructionContributor