Use StructureMap and Castle DynamicProxy to easily change the semantics of your code

In this posting my intentions are to show you how to use Inversion of Control (IoC), with the help of StructureMap, for being able to easily switch the semantics of e.g entities in a model with the change of a few lines in the StructureMap configuration. I will use it to go from plain classes to dynamically generated proxies, using Castle DynamicProxy. The proxied version will add the attributes: Serializable and DataContract. I will not implement any interception, but I will setup a empty interceptor which, if you want, you can extend and play with for yourself.

Ok, even if this might not be the most useful scenario (as it was something I fiddled around with) it shows you how easily it is to control your dependencies(when the infrastructure code is in place). E.g. Lets say that I’m using Entity framework 4 (EF4) and the new capabilities of Code-only and POCO entities and I let EF4 generate proxies to keep track of changes etc. I could then instruct StructureMap to let EF4 create the instances for me at all time and not just when I fetch allready persisted entities.

The solution – Pls.ProxyLab

Pls.Core

Contains some simple “reusable” infrastructure code that could be references by all other assemblies.

Pls.ProxyLab.Client

Simple Console application that consumes and outouts some metadata information about the entities.

Pls.ProxyLab.Entities

Contains the entities of the model

Pls.ProxyLab.IoC

Contains the StructureMap-based IoC-container.

Pls.ProxyLab.IoC.Configuration

Contains the congifurations for the StructureMap-based IoC-container. In this demo I have also put the configuration of the ProxyBuilder in this assembly.

The model

To keep things simple I have not included anything else than simple automatic properties and constructors in my entities.

The entity model of the Pls.ProxyLab

A little note about the constructors. As you will se they are only used for initialization of default values and for resolving dependencies between entities. With the use of StructureMap, I actually wouldn’t need the resolving of the other entities, since I could let StructureMap handle this by autowiring dependencies using property setter injection. The reason to why I’m resolving it in the model is that: It shows the intent more clearly and I also couldn’t get StructureMap to handle the dependencies when I was generating proxies.

All members are made virtual so that Castle DynamicProxy can create proxies and intercept the members.

Entity

A simple base class that (when I start incorporating persistancy) will contain implementation for Identity and Concurrency tokens etc. As of right now it’s an empty shell.

public abstract class Entity
{
}

Person, Customer and Room

Simple classes that extends the Entity baseclass with some automatic properties.

public class Person
    : Entity
{
    public virtual string Firstname { get; set; }
    public virtual string Lastname { get; set; }
}
public class Customer
    : Person
{
    public virtual string CustomerNo { get; set; }
}
public class Room
    : Entity
{
    public virtual string RoomNo { get; set; }
}

BookingRequest

Just a little bit more complicated, as it set’s some default values for its members.

public class BookingRequest
    : Entity
{
    public virtual int NoOfAdultBeds { get; set; }
    public virtual int NoOfChildBeds { get; set; }
    public virtual bool SmokingAllowed { get; set; }
    public virtual bool WantsWindow { get; set; }

    public BookingRequest()
    {
        NoOfAdultBeds = 2;
        NoOfChildBeds = 0;
        SmokingAllowed = false;
        WantsWindow = true;
    }
}

Booking

Not so complicated. The only thing that is new is that is resolves some dependencies to other entities.

public class Booking
    : Entity
{
    public virtual BookingRequest Request { get; set; }
    public virtual string BookingNo { get; set; }
    public virtual Customer Customer { get; set; }
    public virtual Room Room { get; set; }

    public Booking()
    {
        Request = EntityFactory.Instance.GetInstance<BookingRequest>();
        Customer = EntityFactory.Instance.GetInstance<Customer>();
        Room = EntityFactory.Instance.GetInstance<Room>();
    }
}

EntityFactory

I have choosen not to talk directly to my IoC-container, but via a simple singleton based EntityFactory, which in turn communicates with the IoC-Container (ProxyLabObjectContainer). I think it gives a more clean naming and understanding of what’s actually being resolved, and I can add a generic constraint so that only entities can be resolved.

public class EntityFactory
{
    public static EntityFactory Instance
    {
        get { return Singleton<EntityFactory>.Instance; }
    }

    public virtual T GetInstance<T>()
        where T : Entity
    {
        return ProxyLabObjectContainer.Instance.GetInstance<T>();
    }
}

Consuming the model

The code for consuming the model is as simple as:

var booking = EntityFactory.Instance.GetInstance<Booking>();

booking.Customer.Firstname = "Daniel";
booking.Customer.Lastname = "Wertheim";
booking.Request.NoOfAdultBeds = 1;
booking.Request.WantsWindow = false;

The StructureMap based IoC-container

The EntityFactory consumed something called ProxyLabObjectContainer which is an IoC-container that uses StructureMap for resolving the objects. The project (Pls.ProxyLab.IoC) only contains one class, the IoC-container, which extends a baseclass from Pls.Core. The only thing it does is to tell StructureMap to look for configurations (in the form of specific StructureMap Registry implementations) in the assembly Pls.ProxyLab.IoC.Configuration, or rather the assemblyname of the assembly containing the IoC-container + .Configurations.

Configuring the IoC-container – Step 1

public class ProxyLabObjectContainer
    : StructureMapObjectContainer
{
    private static string _configurationNamespace 
        = typeof (ProxyLabObjectContainer).Namespace + ".Configuration";

    public static IObjectContainer Instance
    {
        get
        {
            return Singleton<ProxyLabObjectContainer>.Instance;
        }
    }

    protected override void BootstrapContainer()
    {
        Container.Configure(x => x
            .Scan(scanner =>
                      {
                          scanner.Assembly(_configurationNamespace);
                          scanner.LookForRegistries();
                      })
            );
    }
}

Configuring the IoC-container – Step 2

Create a StructureMap Registry implementation that tells the IoC-container how-to resolve the entities. I do this by telling it to scan a specific assembly for all types that extends Entity. I also explicitly exclude the type Entity, since it is abstract and shall not be resolved.

[Serializable]
public class IoCRegistry
    : Registry
{
    public IoCRegistry()
    {
        Scan(s =>
                {
                    s.AssemblyContainingType<Entity>();
                    s.AddAllTypesOf<Entity>();
                    s.ExcludeType<Entity>();
                });
    }
}

Take it for a testride

If we run the application now (which will output information to the console about extended baseclasses, implemented interfaces and attributes) it will not output that much. No interfaces and no attributes, just the baseclass Entity and ultimately System.Object.

Start using proxies instead

Ok, lets pretend I want to use my entities in a WCF scenario, and I want to implement the attributes: Serializable and DataContract. Instead of adding this manually to my classes I will generate proxies for the classes and inject these attributes.

To get acquainted with Castles DynamicProxy (CDP) I have built my own custom API that wraps the funtionality of CDP. All that code is placed in the Pls.Core assembly. I have an interface that defines my custom IProxyBuilder.

ProxyBuilder

public interface IProxyBuilder
{
    IProxyConfig Config { get; set; }

    object ProxyFromClass(Type proxiedClassType, params IInterceptor[] interceptors);

    T ProxyFromClass<T>(params IInterceptor[] interceptors)
        where T : class;

    object ProxyFromInterface(Type proxiedInterfaceType, params IInterceptor[] interceptors);

    T ProxyFromInterface<T>(params IInterceptor[] interceptors)
        where T : class;
}

The intentions are quite clear: A proxybuilder can create proxies using either classes or interfaces as templates. Either using generics or by passing Types. This is only a fraction of all the overloads and possibilities that Castles DynamicProxy (CDP) offers, so my wrapping interface also gives me a cleaner API and therefore, hopefully, offers less confusions.

The implementation that’s included in Pls.Core is really simple and just forwards the calls to CDP’s ProxyGenerator.

public class ProxyBuilder
    : IProxyBuilder
{
    protected virtual ProxyGenerator ProxyGenerator { get; set; }
    public virtual IProxyConfig Config { get; set;}

    public ProxyBuilder(IProxyConfig config)
    {
        ProxyGenerator = new ProxyGenerator();
        Config = config;
    }

    public virtual object ProxyFromClass(Type proxiedClassType, params IInterceptor[] interceptors)
    {
        return ProxyGenerator.CreateClassProxy(
            proxiedClassType, Config.GenerationOptions, interceptors);
    }

    public virtual T ProxyFromClass<T>(params IInterceptor[] interceptors)
        where T : class
    {
        return ProxyGenerator.CreateClassProxy<T>(
            Config.GenerationOptions, interceptors);
    }

    public virtual object ProxyFromInterface(Type proxiedInterfaceType, params IInterceptor[] interceptors)
    {
        return ProxyGenerator.CreateInterfaceProxyWithoutTarget(
            proxiedInterfaceType, Config.GenerationOptions, interceptors);
    }

    public virtual T ProxyFromInterface<T>(params IInterceptor[] interceptors)
        where T : class
    {
        return ProxyGenerator.CreateInterfaceProxyWithoutTarget<T>(
            Config.GenerationOptions, interceptors);
    }
}

Default ProxyConfig

The ProxyBuilder needs some configuration which is provided by injecting an implementation of my custom IProxyConfig interface. I have made a simple default implementation that I will extend when I setup the configurations to use when creating proxies for my entities.

[Serializable]
public class ProxyConfig
    : IProxyConfig
{
    public virtual ProxyGenerationOptions GenerationOptions { get; private set; }

    public ProxyConfig()
    {
        GenerationOptions = new ProxyGenerationOptions();
    }
}

The EntityProxyConfig

The next step is to create a custom ProxyConfig that I will use to instruct an instance of ProxyBuilder, how-to construct proxies for my entities.

    Instructions:

  • Add Serializable attribute
  • Add DataContract attribute

To achieve this I need to create instances of System.Reflection.Emit.CustomAttributeBuilder and inject them to Castles DynamicProxy’s GenerationOptions.

Serializable – CustomAttributeBuilder

Since this attribute doesn’t have any properties or arguments to provide values for, the cTor overload I need to use is:

public CustomAttributeBuilder(
    System.Reflection.ConstructorInfo con,
    object[] constructorArgs)

Which is done in CreateSerializableAttributeBuilder in EntityProxyConfig.

protected virtual CustomAttributeBuilder CreateSerializableAttributeBuilder()
{
    var attributeType = typeof(SerializableAttribute);
    var ctor = attributeType.GetDefaultCtor();

    return new CustomAttributeBuilder(ctor, new object[0]);
}

The GetDefaultCtor is an extensionmethod that you will find in Pls.Core.

DataContract – CustomAttributeBuilder

This attribute has some properties that I want to pass values to, so I need to use another overload of the cTor of CustomAttributeBuilder:

public CustomAttributeBuilder(
    System.Reflection.ConstructorInfo con,
    object[] constructorArgs,
    System.Reflection.PropertyInfo[] namedProperties,
    object[] propertyValues)

So I need to extract PropertyInfos for the properties I want to set values for (namedProperties) and I need to provide values for them (propertyValues).

protected virtual CustomAttributeBuilder CreateDataContractAttributeBuilder()
{
    var attributeType = typeof(DataContractAttribute);
    var ctor = attributeType.GetDefaultCtor();
    var props = GetPropertiesAndValues(attributeType,
                              new Tuple<string, object>(
                                  "IsReference", DataContractTemplate.IsReference),
                              new Tuple<string, object>(
                                  "Namespace", DataContractTemplate.Namespace));

    return new CustomAttributeBuilder(
        ctor, new object[0],
        props.Select(p => p.Item1).ToArray(),
        props.Select(p => p.Item2).ToArray());
}
protected virtual IEnumerable<Tuple<PropertyInfo, object>> GetPropertiesAndValues(
    Type type, params Tuple<string, object>[] nameValues)
{
    return nameValues.Select(
        nameValue => new Tuple<PropertyInfo, object>(
            type.GetProperty(nameValue.Item1), nameValue.Item2)).ToList();
}

A short explanation. I pass simple Tuples with the name of the property I want and the value I want to provide for it:

  • new Tuple(“IsReference”, DataContractTemplate.IsReference)
  • new Tuple(“Namespace”, DataContractTemplate.Namespace)

So I’m obviously interested in specifying two properties: IsReference and Namespace.

I pass these tuples to a simple helper: GetPropertiesAndValues which returns Tuples where the name of the property is replaced with a PropertyInfo. Hence you will get back:

  • Tuple(xxx, true)
  • Tuple(xxx, “MyNamespace.Org”)

Ok, so where does the values “true” and “MyNamespace.Org” comefrom. The being able to affect the configuration I have provided some properties of the EntityProxyConfig. One property is the “DataContractTemplate” which is an simple instance of the DataContractAttribute. I have also provided some other properties that can be configured. The values are now sat in the cTor which probably would lie somewhere else, but this is just a demo so…

public virtual bool ApplySerializable { get; set; }
public virtual bool ApplyDataContract { get; set; }
public virtual DataContractAttribute DataContractTemplate { get; set; }

public EntityProxyConfig()
{
    ApplySerializable = true;
    ApplyDataContract = true;
    DataContractTemplate = new DataContractAttribute { IsReference = true, Namespace = "MyNamespace.org" };

    InitializeProxyGenerationOptions();
}

That is the important code of the EntityProxyConfig-class, the rest is just code that forms a process (chain of method calls and simple instructions) to initialize the GenerationOptions. To complete code for the class looks like this:

[Serializable]
internal class EntityProxyConfig
    : ProxyConfig
{
    public virtual bool ApplySerializable { get; set; }
    public virtual bool ApplyDataContract { get; set; }
    public virtual DataContractAttribute DataContractTemplate { get; set; }

    public EntityProxyConfig()
    {
        ApplySerializable = true;
        ApplyDataContract = true;
        DataContractTemplate = new DataContractAttribute { IsReference = true, Namespace = "MyNamespace.org" };

        InitializeProxyGenerationOptions();
    }

    protected virtual void InitializeProxyGenerationOptions()
    {
        var attributeBuilders = CreateAttributeBuilders();

        foreach (var attributeBuilder in attributeBuilders)
            GenerationOptions.AdditionalAttributes.Add(attributeBuilder);
    }

    protected virtual IEnumerable<CustomAttributeBuilder> CreateAttributeBuilders()
    {
        return new[] { CreateSerializableAttributeBuilder(), CreateDataContractAttributeBuilder() };
    }

    protected virtual CustomAttributeBuilder CreateSerializableAttributeBuilder()
    {
        var attributeType = typeof(SerializableAttribute);
        var ctor = attributeType.GetDefaultCtor();

        return new CustomAttributeBuilder(ctor, new object[0]);
    }

    protected virtual CustomAttributeBuilder CreateDataContractAttributeBuilder()
    {
        var attributeType = typeof(DataContractAttribute);
        var ctor = attributeType.GetDefaultCtor();
        var props = GetPropertiesAndValues(attributeType,
                                  new Tuple<string, object>(
                                      "IsReference", DataContractTemplate.IsReference),
                                  new Tuple<string, object>(
                                      "Namespace", DataContractTemplate.Namespace));

        return new CustomAttributeBuilder(
            ctor, new object[0],
            props.Select(p => p.Item1).ToArray(),
            props.Select(p => p.Item2).ToArray());
    }

    protected virtual IEnumerable<Tuple<PropertyInfo, object>> GetPropertiesAndValues(
        Type type, params Tuple<string, object>[] nameValues)
    {
        return nameValues.Select(
            nameValue => new Tuple<PropertyInfo, object>(
                type.GetProperty(nameValue.Item1), nameValue.Item2)).ToList();
    }
}

Configure StructureMap to use the ProxyBuilder

If I would like to consume the ProxyBuilder without using StructureMap I would use it like this:

var proxyBuilder = new ProxyBuilder(new EntityProxyConfig());
var bookingItem = proxyBuilder.ProxyFromClass<Booking>(new EntityInterceptor());

I will then get a proxied version of my Booking entity and all calls to its virtual members will be intercepted in my custom EntityInterceptor (more about this later).

Remember the IoCRegistry class that scanned the Pls.ProxyLab.Entities assembly for Entity-implementations? We need to add one single line to it, so that we don’t use StructureMaps default convention, but instead our custom EntityConvention, which in turn will specify that the ProxyBuilder should be used.

The line to be added is:

s.Convention<EntityConvention>();

I will also let the IoC-container be responsible of creating my IProxyBuilder implementation as a Singleton:

For<IProxyBuilder>()
    .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton))
    .Use<ProxyBuilder>()
    .Named("EntityProxyBuilder")
    .Ctor<IProxyConfig>().Is<EntityProxyConfig>();

So the complete code now looks like this:

[Serializable]
public class IoCRegistry
    : Registry
{
    public IoCRegistry()
    {
        //Add proxybuilder that are used for creation of my entities
        For<IProxyBuilder>()
            .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.Singleton))
            .Use<ProxyBuilder>()
            .Named("EntityProxyBuilder")
            .Ctor<IProxyConfig>().Is<EntityProxyConfig>();

        //Add all entities
        Scan(s =>
                {
                    s.Convention<EntityConvention>();
                    s.AssemblyContainingType<Entity>();
                    s.AddAllTypesOf<Entity>();
                    s.ExcludeType<Entity>();
                });
    }
}

EntityConvention

Only one thing left to implement, the EntityConvention that will be used to register all the found Entity implementations.

[Serializable]
internal class EntityConvention
    : IRegistrationConvention
{
    public void Process(Type type, Registry registry)
    {
        registry.For(type).Use(
            ctx =>
            {
                var proxyBuilder = ctx.GetInstance<IProxyBuilder>("EntityProxyBuilder");

                return proxyBuilder.ProxyFromClass(type, new EntityInterceptor());
            });
    }
}

I simply use the previously registrered IProxyBuilder for entities and uses it to create a proxied representation of the specific Entity implementation. I provide my custom EntityInterceptor so that I can intercept interactions made to the virtual members of my entities.

The interceptor is currently empty and just lets all calls pass through.

[Serializable]
internal class EntityInterceptor 
    : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
    }
}

Take it for a testride

Ok, this time the IoC-container will return proxied entities, hence we will get another output.

Proxied entities

As you can see we are now getting proxies of our entities and they have all gained the injected attributes.

That’s it for now. As always you can download the complete code here.

//Daniel

2 thoughts on “Use StructureMap and Castle DynamicProxy to easily change the semantics of your code

  1. Pingback: DotNetShoutout

  2. Very helpful article. I think the attached source code is incomplete, I can only generate the proxy class by doing:

    var proxyBuilder = new ProxyBuilder(new EntityProxyConfig());
    var bookingItem = proxyBuilder.ProxyFromClass(new EntityInterceptor());

    Using the EntityFactory still pulls back the entities without a proxy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s