I've been delving into DLR and dynamic types as of late; in particular, how to enforce a static "contract" (an interface per se) on a dynamic type. During my perusal of blogs and articles, I came across an article by Tobi that delved into what I was trying to do, but not in a generic fashion. The interesting bit of it is that Tobi referenced another open source project called the Castle Project. This project, among other things, has some utility methods that allow developers to create class proxies and implement interfaces at runtime.The proxied objects could then have their method and property calls specially handled by an IInterceptor implementation. So, after reviewing of the code and a little bit of hacking, I came up with runtime duck typing solution:
dragon = Dragon()
public interface Duck
public class Cow
public void Quack()
static void Main(string args)
ScriptEngine pythonEngine = Python.CreateEngine();
ScriptRuntime runtime = pythonEngine.Runtime;
ScriptScope scope = runtime.ExecuteFile("hello.py");
IDynamicObject dynamicObject = (IDynamicObject)scope.GetVariable("dragon");
// I can't figure out how to do this without the runtime?
// Using GetMetaObject and building an expression tree?
Duck dragon = DuctTapeHelper.DuctTape<Duck>(dynamicObject, runtime);
Duck cow = DuctTapeHelper.DuctTape<Duck>(new Cow());
// Duck Type!
Notice that neither "Cow" or "Dragon" implement the "Duck" interface, but at runtime, an interface proxy is generated to allow them to become Ducks!
Incidentally, another potential way to do this, without the dependency on the Castle Project utilities, is to use reflection to generate a IronRuby/IronPython script that implements an interface proxy.
Here's the full source code to my version of the DuctTape project. I am packaging the various projects from DLR and Castle into it as well. The code is nowhere near complete; it is just a functional prototype to make sure the concepts actually work! I feel that it could be done better through expression trees, but I couldn't figure out how to use an Expression tree to call into a dynamic method on IDynamicObject. Please let me know if you have more insight into this, as I am still a DLR noob.
Does anyone know of a good way to embed code into a blog? As you can see, my line breaks become all messed up with whatever tool I use (I use Live Writer with Paste from Visual Studio or Source Code Snippet).
Blogger has some silly "Convert line breaks" option that is defaulted to Yes. As a result, it completely mangles all line breaks if you have a <pre> tag in your post body. Turn that off, and all is well.