Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : Is there a generic way to forward a method call to another object (with the same interface)?

Tags:

c#

reflection

Is there a way to implement this pattern in a generic way?

A dispatcher object and a bunch of worker objects all derive from the same interface.

Any method call into the dispatcher object needs to be dispatched (forwarded) to one of the worker objects (with all the arguments).

Each method would need to discover it's own name, find the corresponding method in the worker objects, discover the arguments, and then make the call. If possible, not using the variable argument mechanism.

Is there some way to do this? Reflection? Code generation?

like image 397
Ziffusion Avatar asked Oct 26 '10 21:10

Ziffusion


2 Answers

It might not be particularly simple, but it's very solid - take a look at Castle.DynamicProxy: http://kozmic.pl/dynamic-proxy-tutorial/

like image 196
Rob Fonseca-Ensor Avatar answered Sep 25 '22 23:09

Rob Fonseca-Ensor


One possible approach would be to have each method in the dispatcher object raise an event, and have all the worker objects subscribe to that event. (Think this is called a "multicast delegate" pattern).

I suppose this might not be quite as "generic" as you're looking for, but could be a simpler way to achieve mostly the same ends.

like image 29
Tom Bushell Avatar answered Sep 23 '22 23:09

Tom Bushell