Tuesday, April 24, 2007

Enterprise Library 3.0 Policy Injection

A couple posts ago, I wrote about Enterprise Library 3.0. I blogged about the two new blocks, Validation and Policy injection, then I discussed the validation block. Today I am going to talk about the policy injection block a bit.

The policy injection block is Patterns and Practices way of dealing with crosscutting concerns and aspect oriented programming (AOP). I want to make clear that the Policy Injection block is NOT an AOP framework. One of the first questions asked is "What is a crosscutting concern?". A concern is a feature of the application. Concerns that implement features of an object within the application like business logic is a core concern. Crosscutting concerns are features that are common across different objects, like logging and instrumentation. Policy Injection separates the core concerns from the crosscutting concerns.

So lets say I have a business class Called Foo with a method A. Every time method A is called I want to log the time it was called and who executed the call and what data was given to the method parameters and what was returned. Well using policy injection I can apply a policy to the method that automatically executes before and after execution of A. This policy will handle all the logging of required data using the logging block of course.

How does it work? Well that is the interesting part. You see, when a client wants to consume Foo the client needs to call policy factory to get the Foo object. the factory then decides if the class has policies and if so it really creates a Proxy to Foo. The Proxy of Foo looks to the client just like the object Foo, however when the client calls A the proxy can fire all pre and post handlers of the policy, the logging information needed, along with calling A on Foo.

So that is policy injection in a nutshell. As you can see it is a very powerful tool. One problem however, is it makes the code a little more difficult to read. When reading a class a method will be tagged as having a policy, but there is no information on what that policy is. The developer is required to do some hunting to understand it all.
Post a Comment