Search code examples
c#unity-containerinject

Factory pattern with Unity Buildup<T> trouble


My demo code is very simple

using Microsoft.Practices.Unity;
using System;

public interface IDecorator
{
    string GetA();
}

public class Decorations:IDecorator
{

    public string GetA()
    {
        return "temp";
    }
}

public class Base
{

}

public class Derive : Base
{
    [Dependency]
    public IDecorator DerivedDecorations { get; set; }
}


public class Program
{
    private static void Main(string[] args)
    {

        Base bd = new Derive(); // here is the point

        var container = new UnityContainer();
        container.RegisterType<IDecorator, Decorations>();

        container.BuildUp(bd); // bd.DerivedDecorations is null

        Console.WriteLine("Press any key to continue...");
        Console.ReadKey();
    }
}

The DerivedDecorations in Derive class could not be resolved on above case

if we change the code to Derive bd = new Derive(); there is no issue

I am not clear about the reason, because we are using factory pattern, could any one give me some reason of that ?


Solution

  • Have a look at the generic BuildUp-Method overload.

    Unity uses the specified Type of T to examine it´s properties and determine dependencies to be injected.

    In your case, you are not explicitly specifying T but rather rely on type inference, which resolve to class "Base" (as the parameters variable type is of type "Base").

    So either declare your variable accordingly, or try another approach via the non-generic version:

    container.BuildUp(typeof(Derived), bd);
    

    or

    container.BuildUp(bd.GetType(), bd); //which resolves to "Derived"
    

    which in the given example makes currently little sense, but I expect your sample to be broken down for simplicity.