Factory template with Unity Buildup <T> problem

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 class DerivedDecorations

in Derive cannot be resolved in the following case

if we change the code to Derive bd = new Derive();

, no problem occurs

I don't quite understand the reason, because we are using a factory pattern, can anyone give me some reason for this?

+3


source to share


1 answer


Have a look at the general BuildUp-Method .

Unity uses the specified type T to check its properties and determine the dependencies to be inserted.

In your case, you are not explicitly specifying T, but rather relying on the type of output that the "Base" class allows (since the type of the variable parameters is of type "Base").

So, either declare your variable appropriately, or try a different approach with a non-generic version :



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

      

or

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

      

which doesn't make sense at this time in this example, but I expect your sample to be broken for simplicity.

+2


source







All Articles