Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?!

like image 320
user3153878 Avatar asked Feb 14 '15 18:02

user3153878


2 Answers

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.

like image 140
Axel Heer Avatar answered Oct 01 '22 01:10

Axel Heer


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.

like image 22
Jeff Vanzella Avatar answered Oct 01 '22 02:10

Jeff Vanzella