Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically creating a wrapper to implement an interface

Tags:

c#

wrapper

I have some classes that don't implement a certain interface but structurally comply to that interface.

interface IFoo {
    void method();
}

class Bar {  // does not implement IFoo
   public void method() {...}
}

Now, I could write a wrapper around those classes that simply delegate to the wrapped class

class BarWrapper : IFoo {
   Bar bar = new Bar();
   public void method()
   {
      bar.method();
   }
}

But that's lots of tedious work. Can those wrapper classes somehow be generated automatically? Something like:

IFoo foo = CreateWrapper<IFoo>(new Bar());

I'm sure you could do this with Reflection.Emit but I've never used that and it doesn't look very easy at first glance.

Is there an easier way or is there perhaps a library that already implements this?

like image 313
helium Avatar asked Dec 17 '09 08:12

helium


2 Answers

What you're trying to accomplish, is known as duck typing. There are some dedicated libraries that will let you do that, although I haven't used any of them.

With little effort (and some reflection) you can use Castle Dynamic Proxy to do that, using approach outlined here.

If for some reason the interceptor based approach would not be acceptable for you Dynamic Proxy does not support that out of the box (yet), but if you use version 2.2 beta, it would be fairly easy to provide that in a strongly typed manner (without using interceptors), by providing your own proxy type builder (take a look at how mixins are implemented).

like image 132
Krzysztof Kozmic Avatar answered Oct 03 '22 10:10

Krzysztof Kozmic


If you want light and simple Duck typing support, you can also check out: Duck Typing project. It works with .Net 2.0 and newer.

Usage example (taken from David Meyer's site):

public interface ICanAdd
{
    int Add(int x, int y);
}

// Note that MyAdder does NOT implement ICanAdd, 
// but it does define an Add method like the one in ICanAdd:
public class MyAdder
{
    public int Add(int x, int y)
    {
        return x + y;
    }
}

public class Program
{
    void Main()
    {
        MyAdder myAdder = new MyAdder();

        // Even though ICanAdd is not implemented by MyAdder, 
        // we can duck cast it because it implements all the members:
        ICanAdd adder = DuckTyping.Cast<ICanAdd>(myAdder);

        // Now we can call adder as you would any ICanAdd object.
        // Transparently, this call is being forwarded to myAdder.
        int sum = adder.Add(2, 2);
    }
}

Using extension methods, you could simplify it into something like this (simlar to Bart De Smet's syntax)

MyAdder myAdder = new MyAdder(); // this doesn't implement the interface
ICanAdd adder = myAdder.AsIf<ICanAdd>(); // but it quacks like a duck
int sum = adder.Add(2, 2);
like image 34
Groo Avatar answered Oct 03 '22 10:10

Groo