Search code examples
c#expression-trees

Use Expression tree to implement interface by proxying existing implementation


Say I have the following interface and two 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 that will be used in proxy</param>
    public ImplementationBuilder(Dictionary<Type, IPerson> instances)
    {
        _instances = instances;
    }

    public void Setup()
    {

    }

    /// <summary>
    /// this should return the generated instance
    /// </summary>
    public IPerson GetProxy()
    {


        return null;
    }
}

What I wanna do is create a new implementation using an Expression tree, and mix and match the methods from the two (or more) implementations. Basically I want to create a proxy that implements IPerson. So I pass in the instances that will be used and I want to use the Setup method to "configure" the proxy. This would basically be a List or Dictionary, every item should be Method and Type. Should while generating the Proxy using an Expression tree check what implementation to use.

So with

Talk, DutchPerson Lunch, EnglishPerson

The GetProxy method would return (Pseudocode)

public class MergedInstance : IPerson
{
    public void Talk() {

       return DutchPerson.Talk()
    }

    public Lunch() {

       EnglishPerson.Lunch()
    }
}

I mainly want this because the proxied Implementations contain a lot of methods, and I want to be able to use feature flags to switch between implementations.

So am I looking at it in the wrong way and is this even reasonably feasible using Expression trees. And I'm using .NET 4.5.1.


Solution

  • I don't think expression trees are your friends here. Read runtime weaving (proxying). A very easy to understand and use framework is for example the Castle DynamicProxy (http://www.castleproject.org/projects/dynamicproxy/). Read some howtos, and you will find yourself amazed.

    If performance is really critical, I would still try to maybe compose than to generate classes on the fly, but you can try the Reflection.Emit way (as @xantos suggests), that can accomplish the same with faster runtime once the classes are generated (which itself is not fast). Good luck