Monday, June 11, 2007

Enterprise library 3.1 – Policy Injection and Caching Block – Asp.Net 2.0

I’m currently investigating the advantage of upgrading from the version 2 of the Enterprise Library to version 3.1.

One advantage in the existing functionality is the way transactions are handled in the data access block compared with the previous version. Now the escalation to the DTC is prevented when many updates are made to the same database. Since we are firing fifty updates in a single transaction this causes no exception anymore.

The new functionality we will use and that does not require any code change is the rolling text file logger. We wrote something similar but we prefer to switch to the standard one Microsoft provides.

The great new functionality is the caching of the execution of the methods. This kicks in when the same method gets executed twice with the same parameters. The three things you need to do, to use the Policy Injection in combination with the Caching is that the object needs to derive from MarshalByRefObject, apply the caching attribute or use configuration and create the object using the PolicyInjection.Create method.

This creates an overhead for every object that is created and for every function that gets executed so take care where to use this caching block. The overhead is often a minor issue considering the drastic performance gain with caching.

The only issue that I have found till now is with hash code of the objects that are passed as parameters in the function that is enabled for caching. The issue is that since we work in a web environment our objects are destroyed between roundtrips so when a new call comes a new “identical” object is created. This new object has a different hash code since it is a new object.

The way we solved is for our custom defined objects, is to override the GetHashCode function. In this overriden function we check the real content of the object and return our hashcode depending on that. The price is that our GetHashCode is slower then the standard one.

The Policy Injection block is a great way to develop in a more Aspect Oriented way and will help us to focus on writing business logic and less tracing, caching, error handling, validation and other plumbing.