General method for wrapping a function

Say I want to wrap a function in another function in order to add some functions to the wrapped function. But I do not know the return type or parameters in advance, since the methods are generated as a web service proxy.

My first train of thought was using Func<T> . But some functions may return void, in which case Action<T> would be more appropriate.

Now my question is: is there a good general way to achieve this? Is there any template I need to look for?

+4
source share
2 answers

Well, the Facade Pattern comes to mind ... It's not a very automatic way to do something, but it works. Basically, you just set a different interface in front of the proxy server and call it instead. Then you can add whatever functionality you need.

Another way to get close to this is aspect-oriented programming . I used PostSharp (when it was free) to do this in the past. You can do things like adding preprocessing / postprocessing to a function by adding a method / property attribute. AOP components then use code weaving to rewrite your IL to include the code you referenced. Please note that this can significantly slow down the build process.

+3
source

As you say, โ€œI donโ€™t know the return type or the parameters in advance,โ€ I think Dynamic Proxy is what you need.

Unfortunately, I only know about dynamic proxies in Java. But I'm sure there is something similar for C #.

Try Google's โ€œDynamic C # Proxyโ€.

For example, for C # there is an implementation: http://www.castleproject.org/dynamicproxy/

So what is a dynamic proxy?

From the JavaDoc http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html#api :

A dynamic proxy class is a class that implements a list of interfaces specified at runtime , so a method call through one of the interfaces in the class instance will be encoded and sent to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a protected type of proxy object for a list of interfaces without requiring a preliminary generation of a proxy class, for example, with compilation time tools. Method calls for an instance of a dynamic proxy class are sent to the only method in the instance call handler , and they are encoded using the java.lang.reflect.Method object that defines the method that was called and an array of type Object containing the arguments.

+1
source

Source: https://habr.com/ru/post/1387401/


All Articles