views:

80

answers:

1

Suppose I have two types, TypeA and TypeB, that I want to register with Unity. TypeB depends on TypeA so I want to inject TypeA into type B through constructor injection. So I would like to write something like the following and have Unity be smart enough to cascade the resolution for me:

_container.RegisterType<ITypeA, TypeA>();
_container.RegisterType<ITypeB, TypeB>();

How can I tell Unity to resolve TypeA and inject into TypeB?

It looks like this is possible if using a config file, but I don't know how you would do it programmaticaly:

<type name="typeB" type="ITypeB" mapTo="TypeB">
   <lifetime type="Singleton"/>
   <typeConfig extensionType="...">
      <constructor>
        <param name="typeA" parameterType="ITypeA">
           <dependency/>
        </param>
      </constructor>
   </typeConfig>
</type>

Thanks in advance for any suggestions!


EDIT: So, Unity does handle this for me. However, I think my issue is that I have a class with two constructors:

public TypeB(TypeA typeA)
{
    _x = typeA;
}

public TypeB() : this(Something.Value)
{
}

It seems that Unity is having trouble knowing which constructor to use. The first constructor is for unit testing and the second should be used at during runtime. Unity is having trouble with this.

A: 

You do it like this:

class TypeA { }

class TypeB {

[InjectionConstructor]
public TypeB([Dependency] TypeA typeOfA)
{

}

}

Johan Leino