3

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 ?

allencharp
  • 1,101
  • 3
  • 14
  • 31

1 Answers1

2

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.

Community
  • 1
  • 1
earloc
  • 2,070
  • 12
  • 20
  • another hint: maybe it would be possible to not "buildUp" an existing instance, but rather let the factory create an instance via container, in which case the full-type is known. This would infer that "Derived" needed to be registered in the container, also. – earloc May 04 '17 at 14:31