Geeks With Blogs
Rohit Gupta Engaging talk on Microsoft Technologies ....My Resume

Policy injection block has been deprecated in Enterprise Library 5.0, however the ExceptionHandling application block contains ExceptionHandlingCallHandler which was usually found useful when used in conjunction with the Policy Injection App Block.
The purpose of this CallHandler is to handle exceptions using the policies defined in app.config/web.config for the ExceptionHandling app block.

One possible way of using the ExceptionHandlingCallHandler is to use the ExceptionHandlingCallHandler attribute on the methods that need Exception Handling. However the class must be enabled for interception by the Unity interceptors, since the ExceptionHandlingCallHandler attribute enables interception using the Unity Interception framework, hence the containing class should be enabled for interception by the Unity framework.

There are three possible ways of interception:
TransparentProxyInterceptor
InterfaceInterceptor
VirtualMethod interceptor

TransparentProxyInterceptor and InterfaceInterceptors are both interface interceptors and create a proxy around the class that needs interception.
InterfaceInterceptor is much better performing as compared to TransparentProxyInterceptors and hence we should choose InterfaceInterceptors except when we need intercept a class that is MarshalByRef object.
VirtualMethodInterceptor is a Type interceptor hence only works on abstract classes or concrete classes.
The following config shows how to enable a interface for interception:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
  <typeAliases>
    <typeAlias alias="ICountryService" type="Aurionpro.SCMProFit.Business.Kernel.API.Masters.ICountryService, Aurionpro.SCMProFit.Business.Kernel.API" />
  </typeAliases>
  <containers>
    <container>
      <extension type="Interception" />
      <register type="ICountryService" mapTo="Aurionpro.SCMProFit.Business.Kernel.Masters.APIServices.CountryService, Aurionpro.SCMProFit.Business.Kernel">
        <interceptor type="InterfaceInterceptor" />
        <policyInjection />
      </register>       
    </container>
  </containers>
</unity>

In the above unity config, we first need to define the sectionExtension for interception:
<sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
Then while registering the type with unity we also specify that we need this type to be intercepted. in the above example it uses InterfaceInterception for interception and uses the policyIntection Behavior for determining when the type should be intercepted.
Elsewhere in a common config I have defined the following policy :

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
  <containers>
    <container>
      <extension type="Interception" />
      <interception>
        <policy name="OperationContractPolicy">
          <matchingRule name="MatchOperationContract" type="Microsoft.Practices.Unity.InterceptionExtension.CustomAttributeMatchingRule,Microsoft.Practices.Unity.Interception">
            <constructor>
              <param name="attributeType" value="System.ServiceModel.OperationContractAttribute, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" typeConverter="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.AssemblyQualifiedTypeNameConverter, Microsoft.Practices.EnterpriseLibrary.Common"/>
              <param name="inherited">
                <value value="false"/>
              </param>
            </constructor>
          </matchingRule>
        </policy>          
      </interception>
    </container>
  </containers>
</unity>

In the above config I have defined a policy injection behavior which uses a CustomAttributeMatchingRule to check if a method is decorated with a “OperationContract” attribute and if so then the type is selected for Interception by unity. Thus now if the method in ICountryService is also decorated with the ExceptionHandlingCallHandler attribute, then the Exception Handling for such a method will now be enabled.
==============================================================================================================
However if we don’t want to decorate a method with the ExceptionHandlingCallHandler attribute and we need to enable ExceptionHandling purely using Configuration, then we can create a CallHandler which implements ICallHandler and reads the Exception Handling policy configuration from the app.config/web.config. The following shows such an implementation:

public class ExceptionCallHandler : ICallHandler
{
    // Fields
    private ExceptionPolicyImpl exceptionPolicy;
    private int order;
 
    public ExceptionCallHandler(string exceptionPolicyName, int order)
    {
        this.exceptionPolicy = UnityContainerFactory.Instance.Resolve<ExceptionPolicyImpl>(exceptionPolicyName);
        this.order = order;
    }
 
    // Methods
    public ExceptionCallHandler(ExceptionPolicyImpl exceptionPolicy)
    {
        this.exceptionPolicy = exceptionPolicy;
    }
 
    public ExceptionCallHandler(ExceptionPolicyImpl exceptionPolicy, int order)
        : this(exceptionPolicy)
    {
        this.order = order;
    }
 
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        if (input == null)
        {
            throw new ArgumentNullException("input");
        }
        if (getNext == null)
        {
            throw new ArgumentNullException("getNext");
        }
        IMethodReturn return2 = getNext()(input, getNext);
        if (return2.Exception != null)
        {
            try
            {
                if (!this.exceptionPolicy.HandleException(return2.Exception))
                {
                    return2.ReturnValue = null;
                    return2.Exception = null;
                    if (input.MethodBase.MemberType == MemberTypes.Method)
                    {
                        MethodInfo methodBase = (MethodInfo)input.MethodBase;
                        if (methodBase.ReturnType != typeof(void))
                        {
                            return2.Exception = new InvalidOperationException(Resources.CantSwallowNonVoidReturnMessage);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                return2.Exception = exception;
            }
        }
        return return2;
    }
 
    // Properties
    public ExceptionPolicyImpl ExceptionPolicy
    {
        get
        {
            return this.exceptionPolicy;
        }
    }
 
    public int Order
    {
        get
        {
            return this.order;
        }
        set
        {
            this.order = value;
        }
    }
}

We need this class since we need an instance of ExceptionPolicyImpl and I used the same logic to create such an instance, as is specified in the ExceptionHandlingCallHandlerAttribute implementation.
Once we have this, just call this CallHandler to the unity config and all methods that satisfy the MatchingRule (in our case the CustomAttributeMatchingRule which looks for presence of OperationContract attribute on a method) would then call this ExceptionCallHandler. the example config will look like the following:

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
  <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration" />
  <containers>
    <container>
      <extension type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity.EnterpriseLibraryCoreExtension, Microsoft.Practices.EnterpriseLibrary.Common" />
      <extension type="Interception" />
      <interception>
        <policy name="OperationContractPolicy">
          <matchingRule name="MatchOperationContract" type="Microsoft.Practices.Unity.InterceptionExtension.CustomAttributeMatchingRule,Microsoft.Practices.Unity.Interception">
            <constructor>
              <param name="attributeType" value="System.ServiceModel.OperationContractAttribute, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" typeConverter="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.AssemblyQualifiedTypeNameConverter, Microsoft.Practices.EnterpriseLibrary.Common"/>
              <param name="inherited">
                <value value="false"/>
              </param>
            </constructor>
          </matchingRule>
          <callHandler name="EFCallHandler" type="Aurionpro.SCMFramework.Common.Repository.EntityFramework.Interceptor.EntityFrameworkCallHandler,Aurionpro.SCMFramework.Common">
            <constructor>
              <param name="order" value="10"/>
            </constructor>
          </callHandler>
          <callHandler name="ExceptionHandlingCallHandler" type="Aurionpro.SCMFramework.Common.Repository.EntityFramework.Interceptor.ExceptionCallHandler,Aurionpro.SCMFramework.Common">
            <constructor>
              <param name="exceptionPolicyName" value="UIExceptionPolicy"/>
              <param name="order" value="1"/>
            </constructor>
          </callHandler>
        </policy>          
      </interception>
    </container>
  </containers>
</unity>

In the above config we have explicitly added the following extension:
<extension type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity.EnterpriseLibraryCoreExtension, Microsoft.Practices.EnterpriseLibrary.Common" />
and then added a reference to the created ExceptionCallHandler class do perform exception handling using the “UIPolicyException” policy . A sample Exception Handling policy looks like the following:

<exceptionHandling>
  <exceptionPolicies>
    <add name="UIExceptionPolicy">
      <exceptionTypes>
        <add type="System.Exception, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" postHandlingAction="ThrowNewException" name="Exception">
          <exceptionHandlers>
            <add name="Wrap Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.WrapHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
                 exceptionMessage="Exception while updating entity"    
                 wrapExceptionType="Aurionpro.SCMFramework.Common.Repository.Exceptions.RepositoryException, Aurionpro.SCMFramework.Common,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
          </exceptionHandlers>
        </add>
      </exceptionTypes>
    </add>
  </exceptionPolicies>
</exceptionHandling>
Posted on Wednesday, October 19, 2011 11:00 AM | Back to top


Comments on this post: Using ExceptionCallHandler with Unity 2.0

# re: Using ExceptionCallHandler with Unity 2.0
Requesting Gravatar...
Unity 2.0???
You don't have typeAlias'es, thery are called &lt;alias alias=""../&gt; in 2.0.
Are you sure that u r using 2.0?
=======================
Yes The examples i shared was from a working application. so alias does work with Unity 2.0
Left by Rohit Gupta on Aug 06, 2013 6:14 PM

Your comment:
 (will show your gravatar)


Copyright © Rohit Gupta | Powered by: GeeksWithBlogs.net