tags:

views:

754

answers:

2

I've been working with Microsoft's Unity IOC container. There are a bunch of overloads for the RegisterType() method all looking similar to

IUnityContainer RegisterType(Type t, params InjectionMember[] injectionMembers);

I'm wondering when the "injectionMembers" parameters are for? I couldn't find any documentation for the them (even though they're in every overload) and none of the sample code I looked at use them.

Am I missing something here? Are they not commonly used or did I just miss the examples?

+2  A: 

The overload with the InjectionMember array is used, when you do not provide a configuration file, that the Unity container tells how to create an instance of the given type or if you want to create an instance on an other way than it is defined in the configuration file.

This overloads are used, when you want to configure an unity container without an configuration file. An InjectionMember can be an constructor, property or method call.

The following code, taken from the Unity help, shows how to use InjectionMembers through the fluent interface of the container.

IUnityContainer myContainer = new UnityContainer();
myContainer.Configure<InjectedMembers>()
  .ConfigureInjectionFor<MyObject>( 
    new InjectionConstructor(12, "Hello Unity!"), 
    new InjectionProperty("MyStringProperty", "SomeText"));

The following xml configuration is equal to the code above.

<type type="MyObject" mapTo="MyObject" name="MyObject">
  <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration"> 
    <constructor> 
      <param name="someInt" parameterType="int"> 
        <value value="12"/>
      </param> 
      <param name="someText" parameterType="string">
        <value value="Hello Unity!"/>
      </param> 
    </constructor> 
    <property name="MyStringProperty" propertyType="string">
      <value value="SomeText"/>
    </property>
  </typeConfig> 
</type>
Jehof
There are many parts of the Unity container I haven't felt a need to use yet. Your example hit on several of them (XML configuration, PropertyInjection, and configuring constant parameters to be injected. Thanks for pointing me in the right direction! I may not need them now, but it's nice to be aware of what's available.
Scott Bussinger
A: 

Also note that although they show up in each overload, they are not required.

I think this works because InjectionMemeber is an array type and is the last parameter, so you can have zero or more comma separated values and the array gets assembled auto-magically...

Mike Graham
Almost. It's because of the params keyword.
Erik van Brakel