You are here: Home Blog Adaptation - adapters for .NET

Adaptation - adapters for .NET

by Dan Fairs last modified Jun 19, 2007 09:57 PM
I've started work on Adaptation, a small framework to implement adapter registries and object adaption in .NET. It's based (as far as C# allows) on the adapter functionality in Zope 3.

I've always liked the way Zope 3 adapters work. They pave the way to being able to write small, reusable components. If you don't know much about how this works in Zope, Jeff Shell posted a great explanation of it.

So how is this different from the decorator pattern that you're probably already familiar with? Well, a decorator usually completely wraps the context object, providing both its own interface (usually by implementing lots of proxies) and the target interface. Adapters are slightly different in that they only provide methods and properties specified by the interface being adapted to. This makes the code for an adapter substantially smaller than that of the equivalent decorator.

Adapters come into their own when trying to reuse code. Traditionally, inheritance has been one of the principal mechanism of code reuse. If you wanted to use a class in your code, you would simply derive your own class from it with the functionality that you required, and use that. This causes your code to become tightly coupled with that from which you are deriving, and of course if a new base type comes along you have to write another class to derive from it.

Adapters can potentially remove that tight coupling - particularly the way Zope does them. The developer makes declarations (either in Python or ZCML, the Zope Configuration Markup Language) about which adapters are available to adapt from what interface (or class) to another interface.

Now, you may be thinking "Interface? This is Python! Python doesn't have interfaces!" And you'd be right. However, Zope provides the zope.interface module - to find out more, go and read Jeff's post on the details.

So I'm planning to port the idea to .NET. I'm not sure that the clean Python syntax will go across:

adapter = IMyInterface(context)

I suspect the .NET version will have a static registry, exposing methods such as:

Registry.Register(typeof(IAdaptsFrom), typeof(IAdaptsTo), typeof(Adapter));
IAdaptsFrom adaptsFrom = new AdaptsFromImpl();
IAdaptsTo adapter = (IAdaptsTo)Registry.Adapt(adaptsFrom);

But I guess that's why we all prefer Python to C#!

Anyway, enough for now - I'll post a little more when I've got the bones of it working. I'll be making a release on this web site when I've got that far.


Filed under: ,
Add comment

You can add a comment by filling out the form below. Plain text formatting.