Extending classes with IExtensibleObject

Mar 16, 2012 on .NET, WCF

Introduction

One of the key features of Windows Communication Foundation (WCF) is the ability to extend various parts of the framework, by adding and/or replacing behaviours. Many of these extension points are implemented by using the IExtensibleObject interface. This post is going to examine how this works and the reasons for using it.

The IExtensibleObject Interface

Classes implement IExtensibleObject in order to be extendible. The interface is defined in .NET as:

This interface ensures that implementers have a publicly accessible IExtensionCollection, which is the access point for injecting custom behaviour. The example below demonstrates a custom extension being added, via this property, to the InstanceContext in WCF:

Classes that implement this interface will have to define Attach() and Detach() functions. These are called when automatically on an instance, when it is added to a IExtensibleObject.Extensions collection. The owner argument will be the IExtensibleObject class that they are being added to.

Below is a very simple implementation of an extension class for our ExtendableClass. The Attach() and Detach() functions have been implemented simply as console writes.

So, why would I use this?

The real power of the extensions is the way that they can access the extendible object on the Attach() and Detach() functions. They can then interact with any publicly exposed members on this, without the orchestrating code being aware of it.

Below is a different example of IExtensionObject and IExtension that demonstrate this. The NameExtenable is the extension object, which also holds an internal list of names and methods to add and remove names. There is also a method GetNames() that returns a string of all the names it holds.