onsdag den 16. februar 2011

On adding support for StructureMap to Sapit

I got a request for adding support for StructureMap to Sapit, and being the challenge-loving type, of course I set out to implement it. I thought, how hard could it be? As it turned out, quite hard!

What separates StructureMap from Unity, Windsor and PostSharp that Sapit already supports, is that StructureMap does not by itself provide a means to do method interception, which is what Sapit is all about. To apply for instance caching to a method, Sapit needs to intercept the calls to the method, invoke some caching logic, let the method call proceed, and then pick up the return value, cache it and return it to the caller. Without a means to intercept the method call, Sapit has no value.

So what to do? Well, after trying to find a way to intercept the call by manually generating a generic proxy (via the .NET 4 DynamicObject class), I got the idea to use Castle DynamicProxy instead. A lot of third party libraries use DynamicProxy under the covers, because it really is a great tool to gain full control over your objects.

However, so far I've not been able to get it to do, what I want. What I want is to use DynamicProxy within a StructureMap type instantiation interceptor to generate a dynamic proxy object with all the right features. The proxy object should wrap the "real" object, expose the same exact interfac as the real object, and have the same set of attributes applied to each method. Until now, I can make DynamicProxy generate a proxy object, but it does not expose the right interface.

If anybody out there has some documentation on how to use DynamicProxy, or perhaps some sample code demonstrating how to use it, I would really appreciate a hint. Meanwhile I will continue to try implementing StructureMap support in Sapit, and I will keep you informed on any progress.