W
W
wally2021-09-21 20:39:10
.NET
wally, 2021-09-21 20:39:10

How to create a dynamic proxy object based on a class or interface in C#?

Good afternoon,

Java has a feature that allows you to create dynamic proxies based on interfaces or classes. For example, through the JDK mechanism - proxying only the interface, CGLIB, ByteBuddy - proxying classes and interfaces. It looks something like this: https://www.baeldung.com/cglib

Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
    if (method.getDeclaringClass() != Object.class && method.getReturnType() == String.class) {
        return "Hello Tom!";
    } else {
        return proxy.invokeSuper(obj, args);
    }
});

PersonService proxy = (PersonService) enhancer.create();

assertEquals("Hello Tom!", proxy.sayHello(null));
int lengthOfName = proxy.lengthOfName("Mary");
 
assertEquals(4, lengthOfName);


Please tell me, is it possible to do this with built-in C# and .NET tools?

As a result, I need an interface implementation generated at runtime, with an invocation handler. After all, it somehow works in RPC like WCF, so it's feasible. There is such an answer on SO https://stackoverflow.com/questions/8387004/how-to...
But as far as I understand it is a little different.

Help please, who cranked a similar thing (give an example of code, if not difficult)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-09-21
@Yum1

There is www.castleproject.org/projects/dynamicproxy
Based on it, everyone makes all sorts of proxies in runtime that intercept calls to something.
Here is the documentation: https://github.com/castleproject/Core/blob/master/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question