Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method to wrap a function

Tags:

c#

wrapper

Say I want to wrap a function in another function, so to add some functionality to the wrapped function. But I don't know the return type or parameters on beforehand as the methods are generated as a web service proxy.

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

Now my question: is there a nice generic way to achieve this? Is there some pattern I need to look for?

like image 815
fuaaark Avatar asked Dec 21 '11 15:12

fuaaark


2 Answers

Well, the Facade Pattern comes to mind... It's not a very automatic way of doing things, but it works. You basically just put another interface in front of the proxy and call that instead. You can then add any functionality that you desire.

Another way to approach this is with aspect oriented programming. I've used PostSharp (when it was free) to do this this in the past. You can do things like add Pre / Post processing in the function by adding an attribute to a method / property. The AOP components then use code weaving to rewrite your IL to include the code that you've referenced. Note that this can significantly slow the build process.

like image 80
RQDQ Avatar answered Oct 16 '22 10:10

RQDQ


As you say "I don't know the return type or parameters on beforehand", I think a Dynamic Proxy is what you need.

Unfortunately, I know about the Dynamic Proxy in Java only. But I am sure, there is something similar for C#.

Try Googling "Dynamic Proxy C#".

For example, there seems to be an implementation for C# here: 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 such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface. Thus, a dynamic proxy class can be used to create a type-safe proxy object for a list of interfaces without requiring pre-generation of the proxy class, such as with compile-time tools. Method invocations on an instance of a dynamic proxy class are dispatched to a single method in the instance's invocation handler, and they are encoded with a java.lang.reflect.Method object identifying the method that was invoked and an array of type Object containing the arguments.

like image 41
nang Avatar answered Oct 16 '22 10:10

nang