c# - Use Expression tree to implement interface by proxying existing implementation -


say have following interface , 2 implementations.

public interface iperson {     string talk();     void lunch();  }  public class dutchperson : iperson {     public string talk()     {         return "ik spreek nederlands.";     }      public void lunch()     {         eatbroodjekroket();     }      private void eatbroodjekroket()     {      } }  public class englishperson : iperson {     public string talk()     {         return "i speak english.";     }      public void lunch()     {         eatfishandchips();     }      private void eatfishandchips()     {      } }     public class implementationbuilder<t> {      private dictionary<type, iperson> _instances;      /// <summary>     ///      /// </summary>     /// <param name="instances">instances used in proxy</param>     public implementationbuilder(dictionary<type, iperson> instances)     {         _instances = instances;     }      public void setup()     {      }      /// <summary>     /// should return generated instance     /// </summary>     public iperson getproxy()     {           return null;     } } 

what wanna create new implementation using expression tree, , mix , match methods 2 (or more) implementations. want create proxy implements iperson. pass in instances used , want use setup method "configure" proxy. list or dictionary, every item should method , type. should while generating proxy using expression tree check implementation use.

so with

talk, dutchperson lunch, englishperson

the getproxy method return (pseudocode)

public class mergedinstance : iperson {     public void talk() {         return dutchperson.talk()     }      public lunch() {         englishperson.lunch()     } } 

i want because proxied implementations contain lot of methods, , want able use feature flags switch between implementations.

so looking @ in wrong way , reasonably feasible using expression trees. , i'm using .net 4.5.1.

i don't think expression trees friends here. read runtime weaving (proxying). easy understand , use framework example castle dynamicproxy (http://www.castleproject.org/projects/dynamicproxy/). read howtos, , find amazed.

if performance critical, still try maybe compose generate classes on fly, can try reflection.emit way (as @xantos suggests), can accomplish same faster runtime once classes generated (which not fast). luck


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -