Thursday, November 22, 2007

Tip of the day #2: Dynamic proxies

A dynamic proxy is an approach that is not fully natively supported in .net but natively exists in java.

What a proxy means, is to wrap an object with with wrapper that intercepts call to that object and does something in addition.

What is it good for? A naive example is to add a proxy that log calls to methods of an object.

A more real world example is to use proxy in an O/R mapper. The mapper can create proxies on top of the domain object and intercept calls to properties in order to fetch data from the db and track changes to the data that will later be persisted (NHibernate works this way).

The idea of dynamic proxy is to provide an implementation of an interceptor and attach it to the proxy. From now on, all calls to methods will pay through the interceptor which, for the logging example, logs every call to the method. Concrete examples can be found in the link at the bottom of this post.

The .net native implementation for dynamic proxies is by using ContextBoundObject or MarsalByRefObject. This approach is limited since you have to inherit from one of these classes which is not clean.

There are several implementations of dynamic proxies that do not interfere with inheritance hierarchy of your code.
Here are some examples:

1) Castle DynamicProxy

2) DynamicProxy.NET

3) LinFu

No comments: