Property Injection not working in Unity Container 3.0 RRS feed

  • Question

  • User-1207335049 posted

    I want to use Dependency Injection in my unit Test Project. I am using Unity Container version 3.0 to achieve this. The problem I am facing is the object is not getting created. Below is the sample code (dummy code) -

    Registration Code -

    var container = new UnityContainer();

    container.RegisterType<IShape, Circle>();

    Test Class code -

    public class UnitTest
    private Drawing drawing = new Drawing();

    public void Test1()

    Class Drawing Code -

    public class Drawing
    private IShape shape;

    public IShape Shape
    get { return this.shape; }
    set { this.shape = value; }

    public void Draw()
    this.shape.Draw(); // Error - object reference not set to instance of any object.

    It looks like the Drawing object does not have the reference of the Shape object created by Unity. Is there any way I can achieve this?

    Wednesday, July 17, 2013 5:48 PM

All replies

  • User1109032460 posted

    Because you are simply using new to create the Drawing object, you are not letting Unity do any dependency resolution for you.

    So instead of using

    private Drawing drawing = new Drawing();

    you will need to use

    Drawing drawing = container.Resolve<Drawing>();

    Of course, you will not do this as a field initialiser. So you could do it as a test initialiser instead.

    Tuesday, August 13, 2013 11:42 AM