How implement exception handling block using Unity 2.0

Topics: Enterprise Library Core, Exception Handling Application Block, General discussion, Policy Injection Application Block
Dec 29, 2011 at 9:37 AM

Hi,

I want to implement the Exception Application Block using Ent Lib. 5.0 and Unity 2.0. I read that by attaching ExceptionCallHandler('ExceptionPolicyName') attribute to method exception will be handled by the corresponding exception handling policy. But I was unable to configure Web.Config file for the ExceptionCallHandler.

Please help me on the same by providing some guidance and example to configure the ExceptionHandlingBlock.

Dec 30, 2011 at 5:19 AM

In this example, I attribute the Process method with an ExceptionCallHandler and then configure Unity to perform PolicyInjection/Interception.  The Exception Handling Policy replaces the InvalidOperationException with an ApplicationException.

using System;

using Microsoft.Practices.EnterpriseLibrary.Common.Configuration.Unity;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.PolicyInjection;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace UnityExceptionHandling
{
    public interface IService
    {
        void Process();
    }

    public class Service : IService
    {
        [ExceptionCallHandler("ExceptionPolicyName")]
        public void Process()
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer().LoadConfiguration();
            container.AddNewExtension<EnterpriseLibraryCoreExtension>();

            IService service = container.Resolve<IService>();

            try
            {
                service.Process();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception was replaced: " + (e is ApplicationException));
                Console.WriteLine(e.Message);
            }
        }
    }
}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="exceptionHandling" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration.ExceptionHandlingSettings, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <exceptionHandling>
    <exceptionPolicies>
      <add name="ExceptionPolicyName">
        <exceptionTypes>
          <add name="NotImplementedException" type="System.NotImplementedException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
            postHandlingAction="ThrowNewException">
            <exceptionHandlers>
              <add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                exceptionMessage="Oops!  An invalid operation occurred!" replaceExceptionType="System.ApplicationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            </exceptionHandlers>
          </add>
        </exceptionTypes>
      </add>
    </exceptionPolicies>
  </exceptionHandling>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <alias alias="IService" type="UnityExceptionHandling.IService, UnityExceptionHandling" />
    <alias alias="Service" type="UnityExceptionHandling.Service, UnityExceptionHandling" />
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Microsoft.Practices.Unity.Interception.Configuration"/>
    <container>
      <extension type="Interception" />
      <register type="IService" mapTo="Service">
        <interceptor type="InterfaceInterceptor"/>
        <policyInjection/>
      </register>
    </container>
  </unity>
</configuration>

You can also configure this using Policy Injection but using Unity is preferable.

See Configuration Files for Interception for a good document on configuring interception (although not specifically PolicyInjection related).

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

Jan 2, 2012 at 10:52 AM
Edited Jan 2, 2012 at 10:53 AM

Hi,

Thanks for the reply. I try the same line of code that you suggest in last reply. But I get a ResolutionFailedException at

IService service = container.Resolve<IService>();

 

The exception details is

 

Resolution of the dependency failed, type = "PolicyInjectionCallHandler.IService", name = "(none)".
Exception occurred while: Calling constructor Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior(Microsoft.Practices.Unity.InterceptionExtension.CurrentInterceptionRequest interceptionRequest, Microsoft.Practices.Unity.InterceptionExtension.InjectionPolicy[] policies, Microsoft.Practices.Unity.IUnityContainer container).
Exception is: SynchronizationLockException - The read lock is being released without being held.
-----------------------------------------------
At the time of the exception, the container was:

  Resolving PolicyInjectionCallHandler.Service,(none) (mapped from PolicyInjectionCallHandler.IService, (none))
    Resolving Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior,(none)
    Calling constructor Microsoft.Practices.Unity.InterceptionExtension.PolicyInjectionBehavior(Microsoft.Practices.Unity.InterceptionExtension.CurrentInterceptionRequest interceptionRequest, Microsoft.Practices.Unity.InterceptionExtension.InjectionPolicy[] policies, Microsoft.Practices.Unity.IUnityContainer container)

PolicyInjectionCallHandler is my application and its default namespace name. Its a console application.

Please suggest me some way. How it can be resolve?

Jan 2, 2012 at 12:38 PM

Hi,

I resolved the issue by changing the configuration little bit. My changes is

        <interceptionBehavior type="PolicyInjectionBehavior" />
        <!--<policyInjection/>-->
Although I am not able to do same thing using code. Do you have any idea, how can be set the interceptionBehavior to PolicyInjectionBehavior ?

Jan 3, 2012 at 3:10 AM
Edited Jan 3, 2012 at 5:34 AM

In the sample I posted policyInjection and PolicyInjectionBehavior both result in the call handler being invoked in my project.

To configure the same as in the configuration via code it would look like:

IUnityContainer container = new UnityContainer();
container.AddNewExtension<EnterpriseLibraryCoreExtension>();
            
container.RegisterType<IService, Service>(
    "",    
    new Interceptor(new InterfaceInterceptor()),
    new InterceptionBehavior<PolicyInjectionBehavior>());

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

Jan 3, 2012 at 5:07 AM

Hi,

Thanks for your reply.

You answer works for me.

Jan 11, 2012 at 8:12 PM

Hi ,

Thanks for the posting. I tried to run the code, but it kept broken at "throw new NotImplementedException". 

When I "View Details", the stacktrace suggests exception at "...<Process_DelegateImplentation>__1 (IMethodInvocation inputs, GetNextInterceptionBehaviorDelegate getNext)". Continuing running the app, however, I can see that the exceptionPolicy does get executed as I can see the "oops! An Invalid operation occured!" msg

If I replace InterfaceInterceptor with TransparentProxyInterceptor, it works just fine without the code bring broken.

I search over the internet and were unable to find a good explaination. COuld you help? Thanks a lot

Joanne

Jan 12, 2012 at 2:33 AM

I'm not sure I follow what you are seeing.  I copied and pasted the above code into a new VS2008 project and it's running fine.  Although it sounds like your code is also running OK since the exception is being replaced?  Maybe if you posted your project it would provide more info?

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

Feb 26, 2013 at 5:03 PM
gr8 work..
Only error i got was the config you have provide has different dll version then I am refering..

Thanks a lot

Regards,
Rahul Mehta