In this fourth part I’ll examine how to build a simple custom handler that will be used with Policy Injection Application Block. The purpose of the handler is simply dumping to console the name of the called method as well all the parameters with theirs values. Here is the class.
Code is really simple, the only interesting method is the Invoke() that gets called instead of the original method of the wrapped object. This method has two parameters, the first contains all the informations on the method invocation, like: name and value of all parameters; the second parameter is a delegate used to get the next handler delegate in the AOP chain. This is needed because you can add more than one handler to a single method, so you will end up with a chain of interceptors.
Now we need to configure PIAB to insert this handler wherever we need it
I want to set a matching rule for an entire type (red), this type of matching rule has only one property called matches (Green) that will accepts a list of types to intercept, in this example I ask to add handlers only to the ITest interface (blue)
I need to specify a custom handler (red) as handler type, then configure the exact type in the type property of the handler (blue) the Order property can be left to 0 (automatic). You can use the order property to manually define the order in witch the handlers will be called.
Now I can simply fire this code
And gets this output.
From the output you can notice that each invocation of methods belonging to ITest, will result in a call to our custom handler.
Inside an handler you really have great control on what to do, you are not only limited to passive operation like inspecting parameters but you can actively modify the behavior of the function. Let’s show how to swallow all exceptions, and logging them to the console.
With this code the handler first verify if the invocation of the function have raised an exception, if yes it simply dumps the exception message to the console and clear the exception. Now if you add a throw statement in DoAnotherThing function the output will be:
As you can see the execution of the program was not stopped by the exception and the exception is dumped to the console.
In PIAB there is already a handler called Exception Handling Handler that is integrated with Exception Handling Application Block, and is a good starting point in defining centralized rules to handle the exception of applications. But if you need some custom logic you can write your own.