views:

174

answers:

5

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?

A: 

There is no direct equivalent but see How to do Dynamic Proxies in C# for some workarounds:

Background: A dynamic proxy dynamically generates a class at runtime that conforms to a particular interface, proxying all invocations to a single 'generic' method.

Earlier, Stellsmi asked if it's possible to do this in .NET (it's a standard part of Java). Seeing as it's the second time I've talked about it in as many days, I reckon it's worth blogging...

Andrew Hare
+3  A: 

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

Mauricio Scheffer
Yep. There is a set of framework providing this functionality.
Alex Yakunin
+1  A: 

Yes. You derive from the abstract RealProxy class.

Pavel Minaev
You're wrong. RealProxies are used for completely different purpose (.NET Remoting). Moreover, you can't use them for non-MBR types.
Alex Yakunin
RealProxies are used for remoting, but they don't have to be used for that purpose only. You can perfectly well use them to intercept calls in the same process. Furthermore, while they are restricted to MarshalByRefObject for _classes_, the question was about _interfaces_, and RealProxy supports all interfaces (as they're always vtable-dispatched).
Pavel Minaev
A: 

Take a look at PoshSharp as well (AOP framework for .NET) - it can do similar things, but in compile time. Probably you'd prefer the approach it supports.

Alex Yakunin
+2  A: 

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.

JasonTrue
More than one mocking framework. See here http://castleproject.org/dynamicproxy/index.html for very partial list of projects using Dynamic Proxy
Krzysztof Koźmic