Search code examples
c#interceptorcastle-dynamicproxy

Castle.DynamicProxy: CreateClassProxyWithTarget() with Interceptor doesn't work, only CreateInterfaceProxyWithTarget()


I'm trying to create simple logger with Castle.DynamicProxy and IInterceptor, but unable to implement it for class without an interface: IInterceptor code is not executing in this case.

I was able to do that for a class with an interface using CreateInterfaceProxyWithTarget(), but unfortunately it is not convenient enough as our legacy project has huge classes without interfaces. Yes, I can use Visual Studio to extract the interface... But if possible, I'd prefer to avoid it.

using Castle.DynamicProxy;

var generator = new ProxyGenerator();
var interceptor = new Interceptor();

// works, but requires the interface
//var sampleClass = generator.CreateInterfaceProxyWithTarget<ISampleClass>(new SampleClass(), interceptor);

// doesn't work
//var sampleClass = generator.CreateClassProxy<SampleClass>(interceptor);
// doesn't work too
var sampleClass = generator.CreateClassProxyWithTarget(new SampleClass(), interceptor);
sampleClass.Method1();
sampleClass.Method2();

public class Interceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
        Console.WriteLine($"Method {invocation.Method.Name}.");
    }
}

public interface ISampleClass
{
    void Method1();
    void Method2();
}

public class SampleClass : ISampleClass
{
    public void Method1()
    {
        Console.WriteLine("Executing Method 1...");
    }
    public void Method2()
    {
        Console.WriteLine("Executing Method 2...");
    }
}

Solution

  • The whole day I tried to solve this issue... And only after publishing to StackOverflow I understood what is wrong: a proxy against instantiated class can't override non-virtual methods.

    So, either interface, or virtual methods.

    I would be happy if someone will propose simplest approach, but for now I have to generate interfaces.