Wednesday, November 16, 2011

Add implied interface to a class.

Often... Well often enough, I need to use a .net framework class to implement a method. I almost always find that I want to use an interface on my class, so I can unit test it, and that the framework class provides no interface. This leads to me needing to define a interface, and implement it with a quick decorator around the framework class. Recently I was doing this with the Ping class when I decided to invest a little time looking for a better answer.

My first attempt was to use spring.net mix-ins, or introductions in AOP terms. That kinda worked, but since mixing require a class with the interface implementation, I still needed to write the decorator... not a whole lot better.

After more googling, turns out what I wanted is called duck-typing (who knew). And as with other problems, once you get the term, the googling is easy. I found a few different libraries that could help, I settled on impromptu.

It did take me a while to work out a good way of integrating with spring.net, i've used spring.net a fair bit, but haven't done a lot of extension work to date. Finally I settled on a custom factory object, it requires the target objec rand target interface, using that, it produces a ready to go decorator.
/emote "<-- nods and files away a new tool for the toolbox"

A quick sample class:

No comments:

Post a Comment

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...