Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the .Net equivalent of Java's Dynamic Proxies?

In java it's possible to dynamically implement an interface using a dynamic proxy, something like this:

public static <T> T createProxy(InvocationHandler invocationHandler, Class<T> anInterface) {
    if (!anInterface.isInterface()) {
        throw new IllegalArgumentException("Supplied interface must be an interface!");
    }
    return (T) Proxy.newProxyInstance(anInterface.getClassLoader(), new Class[]{anInterface}, invocationHandler);
}

Is there an equivalent in .Net?

like image 695
Darren Avatar asked Jul 16 '09 17:07

Darren


2 Answers

There are several libraries that implement this in .NET. Here's a list of them, with a benchmark.

like image 113
Mauricio Scheffer Avatar answered Sep 20 '22 23:09

Mauricio Scheffer


The most widely used one is the Castle Project's Dynamic Proxy, which is also used by several (or at least 1) mocking frameworks. Keep in mind that methods (and sugared-up methods like properties) are not virtual by default in dotnet, so that can create some headaches if you weren't anticipating it in your class design.

like image 32
JasonTrue Avatar answered Sep 22 '22 23:09

JasonTrue