Category: Castle

Castle Dynamic Proxy 2.2 beta in the wild!

Jono just pushed the first beta version of the Castle Dynamic Proxy 2.2 to the SourceForge.

Don’t let the minor version number mislead you – this is a substantial improvement over the version 2.1. The changelog contains over 40 positions. I’m going to go over the most important ones here.

  • Official support for Silverlight 2 or newer.
  • Last version to support .NET 2.0.
  • Substantial performance improvements (which includes more aggressive caching). Just see this:
    dp_perf
    If you’re interested the code for this pseudo-benchmark is here.

Notice that this benchmark measures only time it takes to generate certain number of distinct proxy types. It is here to outline strengths of new version, and does not serve as reliable comparison. You’re unlikely to observe similar speedup in your application. However if you’re creating many proxy types you will notice better performance. The more proxies, the greater improvement.

  • Better support for medium trust scenarios (you will need .NET 2.0 SP2 for this).
  • Significantly broadened range of supported scenarios around generics.
  • Added logging so that you can gain insight into what DP is doing (see Jonathon’s post here).
  • Improved exception messages, so that they are more descriptive and point to a solution.
  • Changed how proxy types are named so that it looks better in logs.
  • Improved handling of mixins, so that it’s now legal to mix in type that implements the same interface as target type, or proxied type.
  • Improved handling of interface proxies with target interface.
  • Added ability to change not only invocation target but also the proxy target in interface proxies with target interfaces
  • … and many more… see the Changes.txt for the full list.

There are few breaking changes that while should not affect vast majority of users, can affect some.

  • All (almost) interface members are now implemented explicitly by the proxy type. This may affect you if you’re reflecting over the proxy types. There is an exception to this rule – for class proxies, when class implements interface member virtually, that member will be implemented implicitly on the proxy type.
  • invocation.MethodInvocationTarget now always points to the method that overrides proxied method on a target type. This means that it’s null when target is null (for interface proxies).
  • many internally used types changed, but you shouldn’t be affected.

 

Last but not least.

This is a beta release. Remember it may contain bugs. However we feel it’s pretty stable at this point. Download it, use it, and if you find any issues, report them so that we can fix them before the final release.

Link is here.

Castle Windsor lazy loading

I just committed a very cool feature to Castle Windsor/MicroKernel that adds lazy registration capabilities. By lazy registration I mean – you get a chance to register a component right at the spot when it’s about to be resolved.

This enables things like integration with external sources of components, like MEF, or WCF config files, lets you distribute your registration in time so that you don’t have to do all of it upfront and many more.

Behind all of this, is this interface:

/// <summary>

/// Provides lazy registration capabilities to the container.

/// </summary>

/// <remarks>

/// When a component is requested from a container, that has not been registered

/// container loads up all the implementers of this interface and asks them in turn

/// whethere they can provide that component, until it finds one that will.

/// </remarks>

public interface ILazyComponentLoader

{

    /// <summary>

    /// Used by container to allow the loader register component for given <paramref name="key"/> 

    /// and <paramref name="service"/> to the container at the time when it is requested

    /// </summary>

    /// <param name="key">Key of the requested component or null</param>

    /// <param name="service">Type of requested service or null</param>

    /// <returns>Registration that registers component for given key and/or service or null.</returns>

    /// <remarks>

    /// While both key and service can be null reference it is guaranteed that at least one of them will not be null.

    /// When implementer opts in to provide the requested component (by returning not-null registration) it is required

    /// to register component for requested key/service combination (when one of the elements is null, it should be ignored as well).

    /// When implementer does not want to register the requested component it nust return null.

    /// </remarks>

    IRegistration Load(string key, Type service);

}

You can now use it pretty easily, as I will show in a second. Let’s take a trivial example:

[DefaultImplementation(typeof(Implementation))]

public interface IHasDefaultImplementation

{

    void Foo();

}

 

public class Implementation : IHasDefaultImplementation

{

    public void Foo()

    {

        

    }

}

We have an interface, a class that implements it, and an attribute we put on the interface that points to its default implementation (assuming we have many). This example is completely artificial, but that’s not the point.

We still need some implementation of ILazyComponentLoader, that will work with this scenario.

public class Loader : ILazyComponentLoader

{

 

    public IRegistration Load(string key, Type service)

    {

        if (!Attribute.IsDefined(service, typeof(DefaultImplementationAttribute)))

        {

            return null;

        }

 

        var attributes = service.GetCustomAttributes(typeof(DefaultImplementationAttribute), false);

        var attribute = attributes[0] as DefaultImplementationAttribute;

        return Component.For(service).ImplementedBy(attribute.Implementation).Named(key);

    }

}

Our Loader is called by the container when a component is requested, that has not been registered in the container. We then check if type of the service requested has DefaultImplementationAttribute, and if it does we register the component with the default implementation, which then will be resolved.

To wire our loader with the container, we register it with ILazyComponentLoader service just like any other component. Yeah – no additional API to memorize!

var kernel = new DefaultKernel();

kernel.AddComponent<Loader>(typeof(ILazyComponentLoader));

That’s all we need to make this test pass:

[Test]

public void Can_Lazily_resolve_component()

{

 

    var service = kernel.Resolve("foo", typeof(IHasDefaultImplementation));

    Assert.IsNotNull(service);

    Assert.IsInstanceOf<Implementation>(service);

}

The code is available now in the trunk, and you can get latest binaries here.

Technorati Tags:

InterfaceProxyWithTarget / InterfaceProxyWithTargetInterface – what’s the difference?

There seems to be much confusion around two kinds of proxies that Castle Dynamic Proxy provides – InterfaceProxyWithTarget and InterfaceProxyWithTargetInterface. On the surface they both appear to be doing the same thing.

Rule of thumb:

If you’re not sure which one you want – you want the one with the longer, confusing name – InterfaceProxyWithTargetInterface.

InterfaceProxyWithTargetInterface seems to be used less often, which is a shame, because what people really want 99% of the time is actually InterfaceProxyWithTargetInterface. However I suppose due to it’s extremely confusing name, and no clear apparent distinction between InterfaceProxyWithTargetInterface and InterfaceProxyWithTarget people tend to pick just the one with shorter name.

Also in previous versions of Dynamic Proxy (up to, and including v2.1) InterfaceProxyWithTargetInterface had some bugs, and had less overloads, which made it less convenient to use than the other one. This is (going to be) greatly improved in version 2.2 (and is available in the trunk now), so there’s really no reason not to use InterfaceProxyWithTargetInterface.

Why’s that? There are two advantages InterfaceProxyWithTargetInterface provides:

  • when you use InterfaceProxyWithTargetInterface its invocations will also implement IChangeProxyTarget interface which lets you change the target object that the call will be routed to.
  • secondly, and most importantly – InterfaceProxyWithTargetInterface make much better use of cache.

The second one, is actually the most important difference, and as you most of the time won’t care about changing invocation target, you most certainly want to use caching as much as possible. In case of InterfaceProxyWithTargetInterface type of the target object is not taken into account, whereas for InterfaceProxyWithTarget it is. If that’s not clear enough, let’s see that in code:

var proxy1 = generator.CreateInterfaceProxyWithTargetInterface<IOne>(new One());
var proxy2 = generator.CreateInterfaceProxyWithTargetInterface<IOne>(new OneTwo());
Assert.AreEqual(proxy1.GetType(), proxy2.GetType());
 
var proxy3 = generator.CreateInterfaceProxyWithTarget<IOne>(new One());
var proxy4 = generator.CreateInterfaceProxyWithTarget<IOne>(new OneTwo());
Assert.AreNotEqual(proxy3.GetType(), proxy4.GetType());

Technorati Tags: ,

Castle Dynamic Proxy tutorial part XV: Patterns and Antipatterns

This is part fifteen of my tutorial on Castle Dynamic Proxy.

We’ve covered almost all of Dynamic Proxy. If you followed along through this series, you now know 95% of Dynamic Proxy 2.1 features that get used 99,9% of the time. Now is the time to wrap up, and with that we’ll review some of the most common pitfalls that you may encounter when developing code on top of Dynamic Proxy.

Leaking this

Consider this simple interface/class pair

public interface IFoo
{
	IFoo Bar();
}

public class Foo : IFoo
{
	public IFoo Bar()
	{
		return this;
	}
}

Now, let’s say we create a proxy for IFoo with target and use it like this:

var foo = GetFoo(); // returns proxy
var bar = foo.Bar();
bar.Bar();

Can you see the bug here? The second call is performed not on a proxy but on a target object itself! Our proxy is leaking its target.

This issue obviously does not affect class proxies (since in that case proxy and target are the same object). Why does not Dynamic Proxy handle this scenario on its own? Because there’s no general easy way to handle this. The example I showed is the most trivial one, but proxied object can leak this in a myriad of different ways. It can leak it as a property of returned object, it can leak it as sender argument of raised event, it can assign this to some global variable, it can pass itself to a method on one of its own arguments etc. Dynamic Proxy can’t predict any of these, nor should it.

In some of these cases there is often not much you can do about it, and its good to know that problem like this exist, and understand its consequences. In other cases though, fixing the issue is very simple indeed.

public class LeakingThisInterceptor:IInterceptor
{
	public void Intercept(IInvocation invocation)
	{
		invocation.Proceed();
		if(invocation.ReturnValue == invocation.InvocationTarget)
		{
			invocation.ReturnValue = invocation.Proxy;
		}
	}
}

You add an interceptor (put it as last one in the interceptors pipeline), that switches the leaking target back to proxy instance. It’s as simple as that. Notice that this interceptor is targeted specifically at the scenario from our example above (target leaking via return value). For each case you will need a dedicated interceptor.

Override equality

One of the most common mistakes when it comes to Dynamic Proxy is not overriding Equals/GetHashCode methods on proxy generation hooks and interceptor selectors, which means you’re giving up caching and that in turn coupled with bugs in BCL means performance hit (plus increased memory consumption).

Solution is very simple, and there’s no exceptions to this rule – always override Equals/GetHashCode methods on all your classes implementing either IProxyGenerationHook or IInterceptorSelector.

As of Dynamic Proxy 2.5 IInterceptorSelector implementations need not override Equals/GetHashCode for the caching to work, since changed proxy generation algorithm now only cares whether selector is present or not.

Make your Proxy Generation Hooks purely functional

Pure function, is a function that for given set of inputs always returns the same output. In case of proxy generation hook, it means that two equal (as specified by overriden Equals/GetHashCode methods) proxy generation hooks will for given type to proxy return the same values from their methods, and when asked again about the same type will again return the same values/throw the same exceptions.

This is a major assumption that Dynamic Proxy makes, and that’s what makes the caching mechanism work. If proxy generation hook is equal to the one already used to generate a proxy type, Dynamic Proxy will assume it would return the same values as the other one, which would result in identical proxy type, so it cuts through the generation process and returns the existing proxy type.

Make your supporting classes serializable

If you’re going to be serializing your proxies, you should make all the classes that go with it serializable. That includes proxy generation hooks, interceptors and interceptor selectors. Otherwise you will get an exception when trying to serialize your proxies. It is not mandatory, but I find it useful. Notice that you will need this also when persisting your proxy assembly to disk.

Use ProxyGenerationHooks and InterceptorSelectors for fine grained control

Do your interceptor’s methods look like this?

public void Intercept(IInvocation invocation)
{
	if(invocation.TargetType!=typeof(Foo))
	{
		invocation.Proceed();
		return;
	}
	if(invocation.Method.Name!="Bar")
	{
		invocation.Proceed();
		return;
	}
	if(invocation.Method.GetParameters().Length!=3)
	{
		invocation.Proceed();
		return;
	}
	DoSomeActualWork(invocation);
}

If they do this often means you’re doing something wrong. Move the decisions to proxy generation hook and interceptor selector

  • Do I ever want to intercept this method? If the answer is no, use proxy generation hook to filter it out of methods to proxy.

Notice that due to bug in Dynamic Proxy 2.1, if you choose not to proxy method on interface proxy, you will get an exception. Workaround for this is to say you want to intercept the method, and then use interceptor selector to return no interceptors for the method. This bug is fixed in Dynamic Proxy 2.2

  • If I do want to intercept this method, which interceptors do I want to use? Do I need all of them? Do I need just a single one? Use interceptor selector to control this.

On the other hand, remember that as every feature this one is also a double edged sword. Too liberal use of proxy generation hooks and interceptor selectors may greatly decrease efficiency of proxy type caching, which may hurt your performance. As always think how much control you need and what the implications on caching will be. Sometimes single if on top of your interceptor is lesser evil than increasing number of proxies required tenfold. As always – use the profiler in scenarios that mimic your production scenarios as closely as possible to check which option is the best for you.

SRP applies to interceptors

SRP stands for Single Responsibility Principle, which means that a class should do just one thing. Many people seem to forget about it when it comes to interceptors. They create one monstrous interceptor class that tries to do all the things they need from Dynamic Proxy – logging, security checking, parameter verification, augmenting target objects with behavior and many more.

Remember that Dynamic Proxy lets you have many interceptors per method call. Use this ability to split behavior between interceptors. You may end up with some general purpose interceptors for things like logging that you use for each intercepted method on each class. As long as all it does is logging – that’s ok.

You may end up with some interceptors that are used for methods on just some classes, like classes inheriting from common base class. As long as these interceptors do just one thing – that’s fine.

You may end up with some interceptors that exist solely for the purpose of intercepting just a single method on specific class or interface. That also is fine. Use interceptor selectors to match interceptors to their respective targets, and don’t be afraid to have multiple interceptors per method.

Technorati Tags: ,

Castle Windsor forwarded types and proxies

Castle Windsor allows you to use single component for multiple services, which is called Forwarded Types.

Forwarded Types

In other words, you can tell Windsor – when IFoo is requested use FooBar as implementation, and when Bar is requested also use FooBar (when using default lifestyle of singleton you’ll get the same instance).

Here’s some code:

var container = new WindsorContainer();
container.Register(Component.For<Bar>().Forward<IFoo>()
                       .ImplementedBy<FooBar>());
var foo = container.Resolve<IFoo>();
var bar = container.Resolve<Bar>();
Debug.Assert(foo == bar);
foo.DoFoo();
bar.DoBar();
Console.ReadKey(true);

Proxies

What if you want to use proxies for that component though?

var container = new WindsorContainer();
container.Register(Component.For<IInterceptor>()
                       .Named("interceptor")
                       .ImplementedBy<FooBarInterceptor>(),
                   Component.For<Bar>().Forward<IFoo>()
                       .ImplementedBy<FooBar>()
                       .Interceptors(new InterceptorReference("interceptor")).Anywhere);
var foo = container.Resolve<IFoo>();
var bar = container.Resolve<Bar>();
Debug.Assert(foo == bar);
foo.DoFoo();
bar.DoBar();
Console.ReadKey(true);

Now, what happens next depends on how you implemented the interface IFoo on class FooBar. Say this is FooBar:

public class FooBar : Bar, IFoo
{
    public void DoFoo()
    {
        Console.WriteLine("DoFoo");
    }
 
    public override void DoBar()
    {
        Console.WriteLine("DoBar");
    }
}

Notice that DoFoo is non-virtual. In this case, here’s what we’re gonna get.

windsor_1

DoFoo did not get intercepted. So what’s the issue here, and how do we fix it?

The What

When you forward a registration, Windsor runs just the first type through the complete registration pipeline, and subsequent forwarded types are treated just as additional piece of data “Oh, by the way, use this component I just registered for this type as well”. Proxy registration is a part of the component model building, and since we end up having just one component only information about its main type gets recorded for proxying.

While this might appear at first clearly as a bug, I think it’s rather a by-design feature. Forcing Windsor to figure it out by itself could pretty quickly become very tricky and we might not always get what we expected. There are however ways of getting what we want.

The fix no 1

Now that we know what we’re up against, how do we fix it? First and the most trivial fix would be simply to make the DoFoo virtual – this way it would get picked when proxying Bar base class and we could successfully proxy it. While this may not always be applicable (you may not be able to modify the class) this is the only option that is available if you’re using the released version. However if you’re using trunk there are two more possible ways of bending it to our will.

Meet my attributes

Due to some changes in how Dynamic Proxy 2.2 (current trunk) handles additional interfaces to proxy, it is possible to intercept non-virtually implemented interface members on a class proxy. Since Windsor by default will request just the class proxy (with no additional interfaces) we need to tell it to toss an IFoo attribute in as well. The quickest way of doing it is throwing an attribute on top of our class:

[ComponentProxyBehavior(AdditionalInterfaces = new[] { typeof(IFoo) })]
public class FooBar : Bar, IFoo
{
    public void DoFoo()
    {
        Console.WriteLine("DoFoo");
    }
 
    public override void DoBar()
    {
        Console.WriteLine("DoBar");
    }
}

If we run the code now we’ll get this:

windsor_2

This is not a solution most people would choose anyway. Even if you can do it (your service does not come from a 3rd party library), you’re decorating your service class with a Windsor-specific attribute which many consider an anti-pattern. There’s however a third, more pure way.

Remember that you need trunk version of Dynamic Proxy for this to work. If you use version 2.1 you’ll end up with this instead:

windsor_3

Windsor will implement the interface, but it will treat it as interface proxy without target. You can make it work by inserting a dedicated interceptor that will forward the calls to your class, but it’s something you’ll have to do manually all the way through.

Black belt approach

I said that forwarded types don’t get ran through whole registration pipeline. However, kernel does raise its component lifecycle events for them, so we can hook up to them and get notified when our forwarding handler gets registered, and modify its component model.

We start by hooking up to kernels HandlerRegistered event, before we register any components.

var container = new WindsorContainer();
container.Kernel.HandlerRegistered += OnHandlerRegistered;

In the OnHandlerRegistered method we check whether the handler at hand is a ForwardingHandler and if so we add its interface to the list of additional interfaces we want to proxy, just like we did using attribute in the example above.

static void OnHandlerRegistered(Castle.MicroKernel.IHandler handler, ref bool stateChanged)
{
    var forwardingHandler = handler as ForwardingHandler;
 
    if (forwardingHandler == null)
        return; //we're only interested in forwarding handlers...
 
    if(!forwardingHandler.Service.IsInterface)
        return; //we're only interested in interface services...
 
    var targetHandler = forwardingHandler.Target;
    if(!targetHandler.ComponentModel.ExtendedProperties.Contains(ProxyConstants.ProxyOptionsKey))
        return; //apparently this service is not registered for proxying
 
    var options = targetHandler.ComponentModel.ExtendedProperties[ProxyConstants.ProxyOptionsKey] as ProxyOptions;
    Debug.Assert(options != null);
 
    options.AddAdditionalInterfaces(forwardingHandler.Service);
}

Now we get our interface proxied without having to touch our component’ code.

Technorati Tags:

Important milestone

SL_build

As of now Dynamic Proxy is passing all the tests under Silverlight. There’s still some work to do, but it is pretty stable the way it is, and it’s been used by Silverlight versions of Rhino Mocks, Moq and probably some others as well for some time.

Castle blogs – RSS feed

One thing I don’t think I articulated clearly enough when announcing Castle Blog Aggregator, was that it comes with RSS feed.

castle_blogs

You may have noticed an RSS icon in your browser when browsing the aggregator site, but in case you didn’t here’s the direct link to the feed that you can use in your favorite feed reader.

We’re also open to include other blogs in the feed, so if you blog about Castle, or know any good blogs about Castle project, let us know, either in the comments, or create a suggestion on Castle UserVoice page.

Technorati Tags:

Castle Dynamic Proxy tutorial part XIV: Persisting proxies

This is part fourteen of my tutorial on Castle Dynamic Proxy.

Wow, what I had planned as few parts tutorial has turned to nothing less than full examination of Dynamic Proxy capabilities. Of all most important features we’ have basically just one left – proxy persistence, which is what we’re going to talk about today.

Discussion

Although Dynamic Proxy’s name suggests that it’s useful for… well creating proxies on the fly at runtime, there are other scenarios where the framework can be useful. We’ve seen one such scenario last time, when we created mixins, not using proxying at all.

Also the dynamic aspect of proxies is not always what we want. This is not so apparent in server application where application starts once and runs (hopefully) for a long time without restart. In the desktop applications however, we might find ourselves creating lots of identical proxies over and over again each and every time user starts the application.

This may degrade the perception of the application from users perspective, because it will take a lot of time to start. When you have many proxy types, things may get quite bad, due to bug in BCL. I call it a bug but it manifests itself by nonlinearly increasing time that creating of each subsequent proxy type takes (Mono apparently does not have this issue. I created a Connect ticket for it here. Please vote on the issue).

In some scenarios using static weaver like PostSharp will be sufficient. However it is not an option if the shape of your proxies depends on some dynamic aspects of user environment, configuration etc. In this case you may not know which proxies and how shaped until your software is on the users machine.

Let’s say you created a WPF application that allows its GUI to be extended with third party extensions, and that you use Dynamic Proxy to dynamically create ViewModels and INotifyPropertyChange on top of your POCO models. Clearly using static weaver is not an option here, because if would defy the whole point of dynamic extensibility.

However once an extension is installed, it’s really no point in recreating proxies for models in it over and over again. Ideally you would want to create them once, the first time you load the extension, and then reuse them… at least until user installs updated version of the extension.

Good news is, (as you probably suspected anyway) it is possible using Dynamic Proxy. There’s no support for determining whether or not you should reuse existing proxies, but this is very scenario specific so having any code for this in the framework itself wouldn’t make much sense anyway. Let’s look at the code.

Let’s see some code

So far we’ve been creating ProxyGenerator instances using default constructor.

var generator = new ProxyGenerator();

If we want to persist our proxies, we have to write more code:

var savePhysicalAssembly = true;
var strongAssemblyName = ModuleScope.DEFAULT_ASSEMBLY_NAME;
var strongModulePath = ModuleScope.DEFAULT_FILE_NAME;
var weakAssemblyName = "Foo.Bar.Proxies";
var weakModulePath = "Foo.Bar.Proxies.dll";
var scope = new ModuleScope(savePhysicalAssembly, strongAssemblyName, strongModulePath, weakAssemblyName, weakModulePath);
var builder = new DefaultProxyBuilder(scope);
var generator = new ProxyGenerator(builder);

We have to create ModuleScope ourselves (which we’ll later use to save the assembly to disk) passing true, as first argument, to tell DynamicProxy that we want to persist the assembly with generated types. If we didn’t do it, we would get an exception if we tried to save the assembly. We then pass two pairs of assemblyname/filename – strongly named and weakly named version. If you intend to use just one (like in this example I’m going to only save weakly named assembly) you can pass the default values for strongly typed version defined as constants on ModuleScope type.

Save me, Save me

That was the first part of the task. We then use the generator to create the proxy types we need, and when we’re done (most likely upon closing the program) we use scope to save the assembly.

scope.SaveAssembly(false);

The argument value of false means that we want to save the assembly without strong name.

generatedProxyAssembly

And after the call the assembly lands safely in the designated folder under the name provided in the constructor. You can now fire up Reflector and see the inner workings of proxy types if that’s what you want.

reflector

One small catch – remember that you only can call save once on a module scope. If you don’t Dynamic Proxy will remind you:

assemblySaveTwiceError

Let’s get it back

We now have just one element missing, that is loading saved types. As I said finding the assembly itself is your responsibility. When you do, and decide to use it, you do it like this:

Assembly proxyAssembly = GetProxyAssembly();
scope.LoadAssemblyIntoCache(proxyAssembly);

The LoadAssemblyIntoCache method will look for proxy types in the assembly and add all it finds to the cache, so that the next time proxy generator asks for type matching one of cached one, that type will be used, instead of creating a new one.

Two things to note here:

You can load more than one assembly into the module scope’ cache (duplicates will be overriden).

You can save the dynamic assembly even after you’ve loaded types from other assemblies to its scope. Note that only types generated in this new assembly will be saved, not the ones loaded from other assemblies (which is pretty logical).

If you want to check before saving if any new types were generated, you can use the following piece of code:

Type[] types = scope.ObtainDynamicModuleWithWeakName().GetTypes();
if(types.Length>0)
{
    //there are new types.
}

Wrapping up

That would basically be it. We pretty much covered every aspect of the framework, and hopefully by now you have pretty good understanding of what and how you can achieve with it. If you think there’s something missing, or you’d like me to talk more about certain topics I already touched let me know in the comments.

Technorati Tags: ,

Castle blogs aggregator

Mauricio, Castle newest committer, long time community member, and our man on StackOverflow.com, did a fabulous job at creating Castle blog aggregator.

You now have one all things Castle RSS feed to subscribe to instead of hunting for content on many various blogs. It has some rules set so that it collects content from only a handful of blogs, skipping posts that are not related to its main topic. It comes mostly from committers and few other blogs that have proven in delivering high quality content. If you know any blogs that you think should be added to the list, let us know, on the list.

You can read, and subscribe to the feed here.

Technorati Tags:

Castle Dynamic Proxy tutorial part XIII: Mix in this, mix in that

This is part thirteen of my tutorial on Castle Dynamic Proxy.

So far we’ve covered most of basic features of Dynamic Proxy, except for one – mixins. Not getting into theoretical details, mixin is an object that stitches many other objects together, exhibiting behaviors of all these objects. Let me illustrate that in pseudo code:

var dog = Dog.New();
var cat = Cat.New();
var mixin = mixin(cat, dog);
mixin.Bark();
mixin.Meow();

In most languages this is achieved through multiple inheritance, but this is not allowed in the CLR, which imposes certain limitations on how mixins are implemented and work in Dynamic Proxy. We can’t have multiple base classes, but we can implement multiple interfaces and this is what Dynamic Proxy uses for mixins. Let’s see an example of how you would use them:

var options = new ProxyGenerationOptions();
options.AddMixinInstance(new Dictionary<string , object>());
return (Person)generator.CreateClassProxy(typeof(Person), interfaces, options);

We’re mixing class Person with Dictionary (which could be useful if you want to attach generic information store to a person). We need ProxyGenerationOptions for that. We add mixin to options using AddMixinInstance method, passing the dictionary we want to use. Next we create class proxy for Person class using the options with mixin. The Person class can by just an any ordinary, non-sealed class.

public class Person
{
	public string Name { get; set; }

	public int Age { get; set; }
}

Notice that none of its properties is virtual nor it implements any interface. That’s ok, because we don’t want to intercept any calls to Person (although we still could, obviously).

Let’s now look at the list of interfaces the proxy implements:

  System.Collections.Generic.ICollection`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Object]] 
  System.Collections.Generic.IEnumerable`1[System.Collections.Generic.KeyValuePair`2[System.String,System.Object]] 
  System.Collections.IEnumerable 
  System.Collections.Generic.IDictionary`2[System.String,System.Object] 
  System.Collections.ICollection 
  System.Collections.IDictionary 
  System.Runtime.Serialization.IDeserializationCallback 
  System.Runtime.Serialization.ISerializable 
  Castle.Core.Interceptor.IProxyTargetAccessor

We have the standard IProxyTargetAccessor, and all the interfaces implemented by generic Dictionary. We can pass around our proxy as Person, but at any time cast it to any of the interfaces and use them.

static void Main(string[] args)
{
	var person = CreateProxy();
	var dictionary = person as IDictionary;
	dictionary.Add("Next Leave", DateTime.Now.AddMonths(4));
	UseSomewhereElse(person);
}

private static void UseSomewhereElse(Person person)
{
	var dictionary = person as IDictionary<string ,object>;
	var date = ((DateTime) dictionary["Next Leave"]).Date;
	Console.WriteLine("Next leave date of {0} is {1}", person.Name, date);
}

Notice that you’re casting the proxy to an interface. If you tried to cast to Dictionary<,> class, you’d get an exception. Out proxy class inherits from Person, not Dictionary<,> – that’s the limitation I talked about. What we have here is a class proxy, mixed with interface proxy with target, in one object. We obviously can mix in more than one object, but there are other limitations.

You don’t specify which mixin interfaces you want to forward to which mixin. This is implicit – if mixin implements an interface, it will be forwarded to that mixin instance, unless someone else implements it as well. You can’t have two mixins that implement the same interface. You can’t have mixin implement same interface as target, nor can you have a mixin implementing one of additional interfaces to proxy. In any of these cases when trying to create a proxy you will get an error.

<

p>This is not a very serious issue though, and I think in most cases it should be enough. In case you need more power, Dynamic Proxy v2.2 will have better support for mixin, allowing scenarios that are not possible in current version.