Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Castle DynamicProxy - 'classToProxy' must be a class

I am probably missing something extremely simple.

I am just trying to write a very minimalistic example of usage of DynamicProxy - I basically want to intercept the call and display method name and parameter value. I have code as follows:

public class FirstKindInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("First kind interceptor before {0} call with parameter {1} ", invocation.Method.Name, invocation.Arguments[0]);
        invocation.Proceed();
        Console.WriteLine("First kind interceptor after the call");
    }
}

public interface IFancyService
{
    string GetResponse(string request);
}

public class FancyService : IFancyService
{
    public string GetResponse(string request)
    {
        return "Did you just say '" + request + "'?";
    }
}

class Program
{
    static void Main(string[] args)
    {
        var service = new FancyService();
        var interceptor = new FirstKindInterceptor();
        var generator = new ProxyGenerator();
        var proxy = generator.CreateClassProxyWithTarget<IFancyService>(service, new IInterceptor[] { interceptor } );

        Console.WriteLine(proxy.GetResponse("what?"));
    }
}

However, when I run it I get a following exception:

Unhandled Exception: System.ArgumentException: 'classToProxy' must be a class Parameter name: classToProxy

What am I missing?

like image 904
Sebastian K Avatar asked Apr 25 '26 15:04

Sebastian K


1 Answers

The error is that CreateClassProxyWithTarget needs to be a type of class not interface. CreateInterfaceProxyWithTarget uses an interface.

like image 147
Dale M Avatar answered Apr 28 '26 09:04

Dale M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!