views:

96

answers:

1

I am trying to update some code from using DynamicProxy to DynamicProxy2. In particular we where using DynamicProxy to provide a mixin of two classes. The setup is something like this:

public interface IHasShape
{
    string Shape { get; }
}

public interface IHasColor
{
    string Color { get; }
}

public interface IColoredShape : IHasShape, IHasColor
{
}

Then assuming some obvious concrete implementations of IHasShape and IHasColor we would create a mixin like this:

public IColoredShape CreateColoredShapeMixin(IHasShape shape, IHasColor color)
{
    ProxyGenerator gen = new ProxyGenerator();
    StandardInterceptor interceptor = new StandardInterceptor();
    GeneratorContext context = new GeneratorContext();
    context.AddMiniInstance(color);

    return gen.CreateCustomProxy(typeof(IColoredShape), intercetor, shape, context);
}

There are no concrete implementations of IColoredShape except as a result of the proxy creation. The StandardInterceptor takes calls on the IColoredShape object and delegates them to either the 'shape' or 'color' objects as appropriate.

However, I've been playing around with the new DynamicProxy2 and can't find the equivalent implementation.

+1  A: 

OK, so if I understand you correctly you have two interfaces with implementations, and another interfaces that implements both of them and you want to mix the implementations of these two interfaces under the 3rd one, correct?

public IColoredShape CreateColoredShapeMixin(IHasShape shape, IHasColor color)
{
    var options = new ProxyGenerationOptions();
    options.AddMixinInstance(shape);
    options.AddMixinInstance(color);
    var proxy = generator.CreateClassProxy(typeof(object), new[] { typeof(IColoredShape ) }, options) as IColoredShape;
    return proxy;
}
Krzysztof Koźmic
Yup I had that much figured out but still couldn't get it to work. In your example the 'shape' object isn't used at all. Is there a simple fix for that?
Jon Palmer
what the shape object should do? What is it for?
Krzysztof Koźmic
I want a pure mixin of the two objects shape and color. Ideally the returned proxy implements an interface that is the combination of IHasShape and IHasColor. That way you can clearly indicate the fact that the proxy has the mixin interface. In this example:http://kozmic.pl/archive/2009/08/12/castle-dynamic-proxy-tutorial-part-xiii-mix-in-this-mix.aspxthe returned mixin is a Person and there isn't much that signals it also is a Dictionary except that you can cast to it. The example I gave first that worked with DynamicProxy1 is exactly what I need.
Jon Palmer
edited the answer
Krzysztof Koźmic