0

I have an object derived from an abstract base class and I want to intercept a method on the object.

Does DynamicProxy support this scenario? I seem to only be able to create proxies by interface or without target but not by abstract base class with a target

public abstract class Sandwich
{
    public abstract void ShareWithFriend();
}

public sealed class PastramiSandwich : Sandwich
{
    public override void ShareWithFriend()
    {
        throw new NotSupportedException("No way, dude");
    }
}

class SandwichInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        try
        {
            invocation.Proceed();
        }
        catch (NotSupportedException)
        {
            // too bad
        }
    }
}

internal class Program
{
    private static void Main()
    {
        var sandwich = new PastramiSandwich();
        var generator = new ProxyGenerator();

        // throws ArgumentException("specified type is not an interface")
        var proxy1 = generator.CreateInterfaceProxyWithTarget<Sandwich>(
            sandwich,
            new SandwichInterceptor());
        proxy1.ShareWithFriend();

        // does not accept a target
        var proxy2 = generator.CreateClassProxy<Sandwich>(
            /* sandwich?, */
            new SandwichInterceptor());
        // hence the method call fails in the interceptor
        proxy2.ShareWithFriend();
    }
}
Jesper Larsen-Ledet
  • 6,625
  • 3
  • 30
  • 42

1 Answers1

0

This works:

var proxy1 = generator.CreateClassProxyWithTarget<Sandwich>(
    sandwich,
    new SandwichInterceptor());
proxy1.ShareWithFriend();
Krzysztof Kozmic
  • 27,267
  • 12
  • 73
  • 115
  • Thanks. That method wasn't available on the version I found on Nuget (Castle.DynamicProxy). Using a newer Castle.Core solved the problem :) – Jesper Larsen-Ledet Sep 01 '11 at 17:51
  • ah ok. `Castle.DynamicProxy` package is obsolete as its description says... there's no way in nuget to make it more visible, or to redirect to `castle.core` nuget, which makes people bump into this issue :| – Krzysztof Kozmic Sep 01 '11 at 21:55