Castle DynamicProxy tutorial part I: Introduction

I’ve been experimenting lately quite a lot with Castle Dynamic Proxy, creating prototype for a project I work on at work and I even implemented a small feature that was missing from it. Generally, Dynamic Proxy (DP from now on) is a great, lightweight framework, but it’s greatest downside is lack of documentation. It’s surprisingly logical a easy to use, but since there are almost no resources on the web, that could help you get started with it, I decided to give it a go, and start a small tutorial series of posts, that will introduce various features of DP while working on a simple sample project.

The project is to add ability to freeze objects, so that from the point in time where object has been frozen, it’s state can not change. AFAIK there’s such feature in WPF, but since my knowledge of WPF is very limited, I don’t know how that works. The project itself is not important (nor the usefulness of its implementation). It’s only purpose is to serve as didactical example. I am also aware that the state of the project shown here is far from how good code should look like. We will evolve the implementation in forthcoming parts of the tutorial, as we introduce other concepts and features of DP.

Basically here’s what we want to achieve:

  • Be able to use non-frozen freezable object just like any other object
  • Be able to check if the object is freezable
  • Be able to check if the object is frozen
  • be able to freeze freezable object
  • NOT be able to change state of the object after it has been frozen

How do we do that? Well, DP creates a transparent proxy for the real objet at runtime for as, and we can intercept the calls to it, and add logic to the objects. This is a very powerful capability and possibilities of using it, are virtually endless.

To specify our requirements, we use tests, using xUnit framework:

[Fact]
public void IsFreezable_should_be_false_for_objects_created_with_ctor()
{
    var nonFreezablePet = new Pet();
    Assert.False(Freezable.IsFreezable(nonFreezablePet));
}
 
[Fact]
public void IsFreezable_should_be_true_for_objects_created_with_MakeFreezable()
{
    var freezablePet = Freezable.MakeFreezable<pet>();
    Assert.True(Freezable.IsFreezable(freezablePet));
}
 
[Fact]
public void Freezable_should_work_normally()
{
    var pet = Freezable.MakeFreezable</pet><pet>();
    pet.Age = 3;
    pet.Deceased = true;
    pet.Name = "Rex";
    pet.Age += pet.Name.Length;
    pet.ToString();
}
 
[Fact]
public void Frozen_object_should_throw_ObjectFrozenException_when_trying_to_set_a_property()
{
    var pet = Freezable.MakeFreezable</pet><pet>();
    pet.Age = 3;
 
    Freezable.Freeze(pet);
 
    Assert.Throws<objectfrozenexception>(delegate { pet.Name = "This should throw"; });
}
 
[Fact]
public void Frozen_object_should_not_throw_when_trying_to_read_it()
{
    var pet = Freezable.MakeFreezable<pet>();
    pet.Age = 3;
 
    Freezable.Freeze(pet);
 
    Assert.DoesNotThrow(delegate { int age = pet.Age; });
    Assert.DoesNotThrow(delegate { string name = pet.Name; });
    Assert.DoesNotThrow(delegate { bool deceased = pet.Deceased; });
    Assert.DoesNotThrow(delegate { string str = pet.ToString(); });
}
 
[Fact]
public void Freeze_nonFreezable_object_should_throw_NotFreezableObjectException()
{
    var rex = new Pet();
    Assert.Throws<notfreezableobjectexception>(() => Freezable.Freeze(rex));
}

We use static class  Freezable to create freezable objects, and to query their state. This allows us to have really simple API (and implementation), and encapsulate all (well, not all – yet) freezable logic in one place. This implementation has one shortcoming that you may have spotted – the class we want to make freezable instance of, has to have default, parameterless constructor.

This is not a DP limitation however, and further along the way, we will remove it.

The way DP works, is by subclassing given class and overriding it’s methods. This approach has few limitations:

  • you obviously can’t proxy sealed class, since it can’t be inherited from
  • you can only override virtual methods, so for non-virtual methods there’s nothing you can  gain

Ok, so how do we go about implementing the whole thing?

First we need some way of tracking which objects are freezable and  their freezability state. For that we create an interface:

internal interface IFreezable
{
    bool IsFrozen { get; }
    void Freeze();
}

It will help us by providing all the information we need.

Then, in our Freezable static class we create a dictionary, that will map objects, to their freezability state:

private static readonly IDictionary<object, IFreezable> _freezables = new Dictionary<object, IFreezable>();

With that, implementation of Freezable methods should be really straightforward:

public static bool IsFreezable(object obj)
{
    return obj != null && _freezables.ContainsKey(obj);
}
 
 
public static void Freeze(object freezable)
{
    if (!IsFreezable(freezable))
    {
        throw new NotFreezableObjectException(freezable);
    }
    _freezables[freezable].Freeze();
}
 
public static bool IsFrozen(object freezable)
{
    return IsFreezable(freezable) && _freezables[freezable].IsFrozen;
}

Still however, no word about DP, and we have implementation of MakeFreezable missing. Also, a reader may point out, that by virtue of keeping some mapping from objects to interface, objects won’t magically gain behavior.

That is true, with a little bit of work however, they will.

What we need to do, is to monitor calls to property setters, and if object is indeed frozen calling a setter should raise an exception, as shown in the test. To do that we need to actually intercept the call, and for that, we have IInterceptor interface.

IInterceptor has only one method:

Castle.Core.Interceptor.IInterceptor.Intercept(Castle.Core.Interceptor.IInvocation);

The IInvocation is another interface that holds all the information about the call.

dptutorial_1_iinvocation

We can query its Method property to get MethodInfo object pointing to the called method, Proceed method, that invokes the method on target object and few other methods and properties that we will examine in forthcoming parts of the tutorial. With that, we have all we need to actually implement our freezable logic:

internal class FreezableInterceptor : IInterceptor, IFreezable
{
    private bool _isFrozen;
 
    public void Freeze()
    {
        _isFrozen = true;
    }
 
    public bool IsFrozen
    {
        get { return _isFrozen; }
    }
 
    public void Intercept(IInvocation invocation)
    {
        if (_isFrozen && invocation.Method.Name.StartsWith("set_", StringComparison.OrdinalIgnoreCase))
        {
            throw new ObjectFrozenException();
        }
 
        invocation.Proceed();
    }
}

Our interceptor holds the freezability state of the object. Since we create one interceptor per object, it will work. In the Intercept method, interceptor checks if the object is frozen, and if called method’s name starts with “set_”, as is the case for all property setters. If indeed that’s the case, it means that we’re trying to set a property of a frozen object, so a ObjectFrozenException is thrown. Otherwise, we can proceed with the call.

Now, it’s really easy to implement Freezable.MakeFreezable method. we know how to intercept calls. The only piece missing is – how do we actually create the proxies. For that, we use the ProxyGenerator class. We only need one instance, so we may keep it as a static field in the Freezable class

private static readonly ProxyGenerator _generator = new ProxyGenerator();

ProxyGenerator class is the heart of the DP library. It has numerous methods for creating different kinds of proxies, but for now, we will only use one: CreateClassProxy, that creates a proxy for a class.

public static TFreezable MakeFreezable<TFreezable>() where TFreezable : class, new()
{
    var freezableInterceptor = new FreezableInterceptor();
    var proxy = _generator.CreateClassProxy<TFreezable>(new CallLoggingInterceptor(), freezableInterceptor);
    _freezables.Add(proxy, freezableInterceptor);
    return proxy;
}

We create a FreezableInterceptor to intercept the calls, verify freezability state of the connected object, and throw if necessary, then we create the actual proxy, add it along with its freezableInterceptor to the dictionary, and return.

In call to CreateClassProxy generic method we pass one more argument – a new instance of CallLoggingInterceptor. It’s a simple class that also implements IInterceptor interface that logs all the intercepted calls to the console. This also means that you can have more than one interceptor for a proxy which is a very powerful and handy capability.

With that, we basically have out initial implementation complete, we only need to create missing exception classes and we are good to go. Indeed, all the tests should pass now.

dptutorial_1_tests_pass

We can create sample console application to see how that works:

internal class Program
{
    private static void Main(string[] args)
    {
        var rex = Freezable.MakeFreezable<Pet>();
        rex.Name = "Rex";
        Console.WriteLine(Freezable.IsFreezable(rex)
                              ? "Rex is freezable!"
                              : "Rex is not freezable. Something is not working");
        Console.WriteLine(rex.ToString());
        Console.WriteLine("Add 50 years");
        rex.Age += 50;
        Console.WriteLine("Age: {0}", rex.Age);
        rex.Deceased = true;
 
        Console.WriteLine("Deceased: {0}", rex.Deceased);
        Freezable.Freeze(rex);
        try
        {
            rex.Age++;
        }
        catch(ObjectFrozenException ex)
        {
            Console.WriteLine("Oups. it's frozen. Can't change that anymore");
        }
        Console.WriteLine("--- press enter to close");
        Console.ReadLine();
    }
}
 
public class Pet
{
    public virtual string Name { get; set; }
    public virtual int Age { get; set; }
    public virtual bool Deceased { get; set; }
 
    public override string ToString()
    {
        return string.Format("Name: {0}, Age: {1}, Deceased: {2}", Name, Age, Deceased);
    }
}

The output of the application looks like this:

dptutorial_1_app

Bah! We get the behavior we wanted, without actually modifying the Pet class, and with surprisingly few lines of code. It may be a little bit overwhelming right now, but what we did, boils down to three things:

  1. We created IInterceptor implementation, that overrides Intercept method and keeps track of freezable state of an object.
  2. We created a proxy object with proxyGenerator.CreateClassProxy method
  3. We created really simple logic to correlate out freezable objects with interceptors, that keep their state.

And with all of that we barely scratched the surface of what can be done with DynamicProxy.

As a bonus, if you are curious how the proxy type generated by DP looks like, here’s what Reflector shows:

dptutorial_1_reflector

If the last screenshot left you with headache don’t worry, by the end of this tutorial it will be all crystal clear.

See you in part II, where we will introduce IProxyGenerationHook, to give us more fine-grained control over our interceptors.

If you have any questions or suggestions please, leave a comment.

The solution with tests is available here.

DynamicProxy I use is the trunk version. You can get the latest version here.

To run tests, you will also need xUnit framework, available here.

Technorati Tags: , ,
  • Excellent tutorial!

    The one very offputting thing in relation to the practicality of using DP – is that fact that you have to declare properties as virtual! – Is there any way around not having to do this?

    Also, in a codebase that I work on, we write lots of manual code to "make" entity types "immutable". Could what you described above be used as a mechanism for developing "immutable" entity types?

  • I don’t understand the reason for the IDictionary<object, IFreezable> to track freezables. Couldn’t you just do a check for the interface in IsFreezable()?
    Could you elaborate?

  • Christopher,
    I did this to simplify the example. This is the first part of the tutorial, I didn’t want to jump into more advanced stuff just yet.
    Dictionary maps simple proxy onto freezable state. I can’t check for the interface, because the proxy does not implement it.

    Take a look at MakeFreezable implementation.

    I create a new interceptor, (which is used to tracking the freezable state of the proxy), then I create the proxy for given class (no additional interfaces) passing the created interceptor, and then I add them both (proxy and its interceptor) to the dictionary.

    I could ditch the dictionary and do that using IProxyTargetAccessor, and even not violate SRP and extract the freezability tracking out of the interceptor and into a mixin, but I didn’t want to introduce this just yet.

  • Many thanks for this…. its nice to see a simple, yet helpful example =)

  • Funny. I’m implementing exactly the same thing using Castle DynamicProxy. When I tried to find a method to determine if a method is a property setter I came to this page 🙂

    You can, BTW, omit the static dictionary memory leak by mixing in the internal interceptor following a controller interface (in my case IFreezableController). Then you can just "cast" to your interceptor and controll the state.

  • Lars,

    I know I can.
    But I didn’t want to introduce all the complexity (and power) of Dynamic Proxy in the 1st part of such a long tutorial 🙂

  • Korvus

    Finally! A morbid tutorial 🙂 The Pet is 50 years old, deceased and now, thanks to the DP, it’s frozen. Cool!

  • @Korvus ROTFLMAO