How do I configure Unity 2.0 Policy Injection to use custom attribute matching rule in configuration file?

Jan 19, 2012 at 4:22 AM
Edited Jan 19, 2012 at 4:30 AM

How do I configure Unity 2.0 Policy Injection to use custom attribute matching rule in configuration file?

What I want is to translate the following code snippet in the unity configuration file.

myContainer.Configure()
       .AddPolicy("MyPolicy")
       .AddMatchingRule
           (new InjectionConstructor(typeof(MyAttributeType), true))
       .AddCallHandler
            ("MyValidator", 
            new ContainerControlledLifetimeManager());

The attributeType requires the Type object of the custom attribute. How do I pass the Type object of my custom attribute in the configuration? Or do I have implement a custom TypeConverter to get the Type object of my custom attribute?

Jan 19, 2012 at 8:29 AM

Yes, I think you will need a TypeConverter.

    public class GetTypeConverter : System.ComponentModel.TypeConverter
    {
        public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, 
            System.Globalization.CultureInfo culture, 
            object value)
        {
            return Type.GetType(value.ToString());
        }
    }
<policy name="MyPolicy">
  <matchingRule name="MyMatchingRule"
    type="CustomAttributeMatchingRule">
    <constructor>
      <param name="attributeType"  type="System.Type, mscorlib">
        <value value="UnityMatchingRule.MyAttributeType, UnityMatchingRule" typeConverter="UnityMatchingRule.GetTypeConverter, UnityMatchingRule"/>
      </param>
      <param name="inherited" type="bool">
        <value value="true" />
      </param>            
    </constructor>
  </matchingRule>
  <callHandler name="MyValidator"
    type="UnityMatchingRule.MyCallHandler, UnityMatchingRule">
    <lifetime type="singleton" />
  </callHandler>
</policy>

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 

Jan 20, 2012 at 4:31 AM

Thanks Randy.