I’ve thought for awhile that the Policy Injection Application Block looked interesting, but now I’ve finally had a chance to use it. The basic idea is that you can wrap a method call with a “handler” which will execute custom code before and after the actual method is executed. The block comes with a bunch of handlers out of the box, but you can also add custom handlers that you can use either by putting a custom attribute on a method or by adding to the configuration file. This post explains in more detail how to use the Policy Injection Application Block.
I’ve taken the Policy Injection Quick Start solution and added a custom handler as an example. Here’s a quick overview of what I did:
- Added four files:
- MyHandler.cs – this is the file where you will write the custom code that you want to execute before and after the actual method call.
- MyHandlerAssembler.cs – creates a MyHandler object from a configuration object.
- MyHandlerAttribute.cs – attribute that creates a MyHandler object when placed on a class, method, or property.
- MyHandlerData.cs – stores data from custom attributes when handlers are created in the configuration file.
- There are two ways to add a handler, and either way will accomplish the same purpose.
- Place a [MyHandler] attribute on a method, property, or class. In the BankAccount.cs class, I decorated the Deposit() method with a [MyHandler] attribute. If you run the application, click the Deposit button, enter a value, and click OK, code in MyHandler.Invoke() will be executed and you’ll see some stuff in the output window.
- Add to the <policyInjection> section of the app.config file. If you open the app.config file and search for “My Custom Stuff” you will find the section that I have added. If you run the app and click the “Balance Inquiry” button, code in MyHandler.Invoke() will be executed and you’ll see some stuff in the output window.
Here is the quick start project with my changes included.
Hope this helps!