Thursday, November 10, 2011

Unity 2 - InjectionMember usage

IUnityContainer RegisterType(Type t, params InjectionMember[] injectionMembers);
What "injectionMembers" parameters are for?

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 another way than defined in the configuration file. The 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();
    new InjectionConstructor(12, "Hello Unity!"), 
    new InjectionProperty("MyStringProperty", "SomeText"));

<type type="MyObject" mapTo="MyObject" name="MyObject">
  <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration"> 
      <param name="someInt" parameterType="int"> 
        <value value="12"/>
      <param name="someText" parameterType="string">
        <value value="Hello Unity!"/>
    <property name="MyStringProperty" propertyType="string">
      <value value="SomeText"/>
  typeConfig> type>
Another use case would be using InjectionFactory. For example:
var container = new UnityContainer();
container.RegisterType(new InjectionFactory((c) => Customer.NewCustomer()));
var newCustomer = container.Resolve();

I use InjectionFactory when there is no chance to add an injection attribute for a third party class constructor or property. In this case you can create delegate creating an object.

0 коммент.:

Post a Comment

Powered by Blogger.