8

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?

5 Answers 5

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yep. There is a set of framework providing this functionality.
5

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.

1 Comment

More than one mocking framework. See here castleproject.org/dynamicproxy/index.html for very partial list of projects using Dynamic Proxy
3

Yes. You derive from the abstract RealProxy class.

2 Comments

You're wrong. RealProxies are used for completely different purpose (.NET Remoting). Moreover, you can't use them for non-MBR types.
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).
1

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.

Comments

0

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.