user3153878
user3153878

Reputation: 421

How use IInterceptor in Castle.DynamicProxy?

I wrote an example like this

Simple Calculator class :

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

implemented "IInterceptor" that provided by DynamicProxy

 [Serializable]
public abstract class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        ExecuteBefore(invocation);
        invocation.Proceed();
        ExecuteAfter(invocation);

    }
    protected abstract void ExecuteAfter(IInvocation invocation);
    protected abstract void ExecuteBefore(IInvocation invocation);
}

Created an Interceptor class and inherited from "Interceptor" class

    public class CalculatorInterceptor : Interceptor
{
    protected override void ExecuteBefore(Castle.DynamicProxy.IInvocation invocation)
    {
        Console.WriteLine("Start");
    }

    protected override void ExecuteAfter(Castle.DynamicProxy.IInvocation invocation)
    {
        Console.WriteLine("End");
    }
}

but when I used it NOT working !!!

static void Main(string[] args)
    {
        ProxyGenerator generator = new ProxyGenerator();
        Calculator c = generator.CreateClassProxy<Calculator>(new CalculatorInterceptor());
        var r = c.Add(11, 22);
        Console.WriteLine(r);
        Console.ReadKey();
    }

I excepted to see something like this :

START
33
END

but only show

33

How I can correct it ?!

Upvotes: 23

Views: 21004

Answers (3)

Jeff Vanzella
Jeff Vanzella

Reputation: 775

The other option is to make an ICalculator interface

public interface ICalculator
{
   int Add(int a, int b);
}

and inherit your class from this interface

public class Calculator : ICalculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

Your dynamic proxy would then use the CreateInterfaceProxyWithTarget method

var proxyGenerator = new ProxyGenerator();

ICalculator calculator = new Calculator()

var proxy = proxyGenerator.CreateInterfaceProxyWithTarget(
    calculator,
    ProxyGenerationOptions.Default,
    new CalculatorInterceptor());

Console.WriteLine(proxy.Add(1, 2));

This gets rid of the virtual from your Calculator class, which in my opinion is bad design unless you have reason to override the method in the future.

Upvotes: 14

Axel Heer
Axel Heer

Reputation: 1883

Try to make the method Add virtual.

public class Calculator
{
    public virtual int Add(int a, int b)
    {
        return a + b;
    }
}

The proxy generator creates a new class inheriting Calculator. Thus, the method Add gets an override to make interception possible.

Upvotes: 24

Silas Reinagel
Silas Reinagel

Reputation: 4203

You have to use the correct overload and pass in both the target object and the interceptor you wish to use. Method should look something like this:

var proxy = generator.CreateClassProxy<Calculator>(new Calculator(), new CalculatorInterceptor() );

Upvotes: 0

Related Questions