Wednesday, December 30, 2009

Unity Application Block – Creating an Handler for exception application block

As mentioned in my previous post, Unity can be used to address cross cutting concerns by registering and invoking interceptors. In this post, I’ll show how to create an Exception handler for the enterprise library exception block using unity to reduce the cross concerns in your code for exception handling.
Step 1: Create ICallHanlder implementation
public class ExceptionCallHandler : ICallHandler
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        var __Result = getNext()(input, getNext);
        if (__Result.Exception == null)
            return __Result;
        var __Rethrow = ExceptionPolicy.HandleException(__Result.Exception, "MyExceptionPolicy");
        if (__Rethrow) throw __Result.Exception;
        else throw new ArgumentException("An exception occured");

    public int Order { get; set; }
Step 2: Create an attribute for Exception Handling
public class ExceptionCallHandlerAttribute : HandlerAttribute
    public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
        return new ExceptionCallHandler();

Step 3: Use the handler attribute in your code.
void Update(T instance);
Step 4: Configure the container
IUnityContainer ___Container = new UnityContainer();
___Container.RegisterType<IRepository<Employee, Guid>, EmployeeRepository>();
___Container.Configure<Interception>().SetDefaultInterceptorFor<IRepository<Employee, Guid>>(new TransparentProxyInterceptor());

It’s that simple to remove the try catch blocks from your code!!!


simi said...


First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I

was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful

for .Net community.

There is a good C# resource site, Have alook


My Blogs said...

Thanks, its helpful. How can we avoid adding the Attribute to the Individual classes. Please provide syntax.