Generics and Castle...

Though I knew you could do it, I never have till today... and that's supplying a type for a generic parameter in another type, which is registered in a container... Of course I didn't have to do it that way, but it it kept the configuration a little thinner.

Basically I have some simple WCF services I wanted to host in a container.. here's the service's interface...

[ServiceContract(Namespace="http://localhost/schemas/testrunner/", SessionMode=SessionMode.Required)]
public interface ITestRunner
Guid StartTestRun(Guid testSuiteId);

TestRunStatus GetRunStatus(Guid testRunId);

To get this to work for my implementation I had to do one thing, which was set the InstanceContextMode to "single" for the service implementations behaviour, otherwise the service host would die when I tried to pass in an instance (it expects a type for any other mode)... I haven't dug very deep into WCF, but it would be nice if they supported a mechanism for supplying a component activator instead...

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class TestRunner : ITestRunner

Now, I build a component for hosting my service... it implements IStartable...

public class HostingWrapper : IStartable
where T: class
private ServiceHost _host;
private T _service;
private ILogger _log;

public HostingWrapper(ILogger log, T service)
if (log == null) throw new ArgumentNullException("log");
if (service == null) throw new ArgumentNullException("service");

_log = log;
_service = service;

public void Start()
_host = new ServiceHost(_service);
if (_log.IsDebugEnabled) _log.Debug("Opening ServiceHost for service: {0}", _service.GetType());
if (_log.IsInfoEnabled) _log.Info("Opened ServiceHost for service: {0}", _service.GetType());

public void Stop()
if (_log.IsDebugEnabled) _log.Debug("Closing ServiceHost for service: {0}", _service.GetType());
if (_log.IsInfoEnabled) _log.Info("Closed ServiceHost for service: {0}", _service.GetType());
_host = null;

And then you just need to regsiter it in the container's configuration:

service="BoatsForGoats.Services.Testing.ITestRunner, BoatsForGoats.Services"
type="BoatsForGoats.Services.Testing.TestRunner, BoatsForGoats.Services" />

type="BoatsForGoats.Services.HostingWrapper`1[[BoatsForGoats.Services.Testing.ITestRunner, BoatsForGoats.Services]], BoatsForGoats.Services" />

About the only tricky thing is that I guessed (incorrectly) that I would only need a single set of square brackets around the generic parameter.

Read More

Blowing up the burner..

Well I blew up my feedburner yesterday... my RSS feed was set to max out at 50 items, which, with my love for pasting html-bloated source code was well over the 256K limit.... but feedburner never bothered tell me it was dead... only noticed today... at any
rate, I tried resetting the size to a max of 6 posts in the feed... and pinging it... but it was still dead, so I did a resync... still no joy... In the end I found that I had to turn
off feed burner support in das blog and then resync the feed.

Moral of the story, don't bloat your feed (It was bad form at any rate, especially in bandwidth starved New Zealand ;o)

If you can see this post it's all working again happily...

Read More compile-time query handling support

Well lots to blog about, but no time to do it... at least not today - at any rate I just thought I would say if you haven't considered using Base4 up until now, why not give it a go with the latest drop :) I'm loving these new changes with the support for Compile-time query handling... I think at this point you can start prototyping stuff with base4 very quickly, between the UI for designing or discovering an existing schema, and now the ability to avoid learning the ObjectPath query syntax it's pretty compelling...

At any rate, as mentioned in the various posts from Alex James, you can now write these kinds of queries:

IItemList matchingFiles = StorageContext.Find(FileBase.Fields.FileSize > 1024000 && FileBase.Fields.MimeType == "audio/wav");

Faboo, and of course you can drill through the relationships:

Track track =  StorageContext.FindOne(Track.Fields.Name == reference.TrackName
&& Track.Fields.Release.Name == reference.ReleaseName
&& Track.Fields.Release.Artist.Name == reference.ArtistName);

This is for a simple hierarchy, where we have Artists-> Releases -> Tracks (sadly organising Music in reality isn't quite this easy...)

But as you can see these queries are getting quite verbose, personally this is where the elegance of this approach comes in... reuse is possible, for example - we can build a static class to hold common queries:

public static class FileBaseQueries
public static ExpressionField LargerThenOneMegabyte
return FileBase.Fields.FileSize > 1024000;

public static ExpressionField MimeTypeIsAudioWav
return FileBase.Fields.MimeType == "audio/wav";

And now the first query could be rewritten:

StorageContext.Find(FileBaseQueries.LargerThenOneMegabyte && FileBaseQueries.MimeTypeIsAudioWav);

The main thing I like about this approach is your queries start looking like sentences... "Larger Then One Megabyte and Mime Type Is Audio Wav"...

Another idea might be to use a method on the static class instead...

public static ExpressionField MimeTypeIs(string type, string subType)
return FileBase.Fields.MimeType == string.Format("{0}/{1}", type, subType);

And then writing something like:

StorageContext.Find(FileBaseQueries.LargerThenOneMegabyte && FileBaseQueries.MimeTypeIs("audio","wav"));

At this point it still reads quite nicely, but it's a little more flexible...

Edit: I just noticed this entry wasn't actually marked as syndicated... fixed it now.
Read More

Intermediate IoC...

I think there's 3 levels of skill involved with the Castle IoC
implementation... first off you get a handle of the XML
configuration, registering components, using existing
facilities... pretty much getting away largely with cut 'n paste

Then you get to the intermediate level.. writing basic
facilities, tweaks to the component model, writing your own sub
dependency resolvers or component activator, having a go with
binsor configuration.

I think the third level is reserved for the Castle team alone...

This post is going to be straddling the beginner to intermediate
kinda level... which is generally all I ever reach with Castle's
IoC... it's not often you have to dig deeper day-to-day... though
it's always good to know there is a lot of untapped potential

So.. for today, say you have a component, like the Base4Host, which has some explicit constructors:

Base4Host(string appName,
int port)


throw new ArgumentNullException("appName");

    if (port
<= 1024)="">throw
new ArgumentOutOfRangeException("port",
"port should be greater then

    _appName = appName;

    _port = port;



Base4Host(string appName,
int port, string root)

    : this(appName, port)


throw new ArgumentNullException("root");   

    _root = root;


You can register it the container easy enough, and provide values
for them in XML configuration, but what if you want to do the
same programatically... generally your first stop would be to
examine the IWindsorContainer for a suitable overload...
alas it doesn't get us far, so we dig in to the underlying
IKernel itself... the kernel exposes some possible

AddComponentWithExtendedProperties(String key, Type classType, IDictionary extendedProperties);

AddComponentWithExtendedProperties(String key, Type serviceType, Type classType, IDictionary extendedProperties);

So you experiment with them, but supplying the dictionary of
extended properties does nothing... hmm... time to file a bug
report? well no... extended properties having nothing to do with
satisfying parameter or property dependencies on your component -
not directly at least.

So why don't we just create the component ourselves.. and then
add it to the container?

Well you can, via the Kernel.AddComponentInstance method
but you're going to miss out on some things... for instance the
startable facility won't be "concerned" with your component, and
as such if it implements IStartable it won't get started
and stopped... Though I haven't confirmed this, I dont think the
container will bother to dispose of any IDisposable
components registered in this fashion either... the container
doesn't consider itself the owner of the component (and generally
this is what we want).

So we're going to have to get a little more intimate with the
container implementation ... so every time a component is
registered in the container a corresponding ComponentModel
is generated for the component, this basically keeps track of
  • Components dependencies
  • Constructor candidates

  • Parameters (sounds like us...)
  • Name, implementation type and service type.
  • Lifecycle, Lifestyle...
  • And some other stuff you can discover for yourself.

Now we could get heavy handed and jump into contributing to
the construction of the component model itself... but it's pretty
uncessary, we just want to tweak the end result... so we can use
an event handler on the Kernel -

So here we have an implementation that solves our problems...
This is being implemented inside a facility, but you could do
this anywhere... wire it up in your custom container that's
derived from WindsorContainer maybe, obviously you want to
remove the if statement for checking the Implemenation type is
Base4Host though. :)

private const string AdditionalParametersKey =


private void
Kernel_ComponentModelCreated(Castle.Core.ComponentModel model)


(model.Implementation == typeof(Base4Host))


        if ((model.Configuration ==



Dictionarystring, object> additionalParameters =
(Dictionarystring, object>)model.ExtendedProperties[AdditionalParametersKey];

foreach (string parameterName in additionalParameters.Keys)








protected override void Init()


    Kernel.ComponentModelCreated +=
new ComponentModelDelegate(Kernel_ComponentModelCreated);


Now I can register my component by doing something like

Dictionarystring, object> additionalParameters =
new Dictionarystring, object>();

additionalParameters.Add("appName", _applicationName);

additionalParameters.Add("port", _port);

additionalParameters.Add("root", _baseDirectory);


Hashtable properties =
new Hashtable();



Kernel.AddComponentWithProperties("base4.defaultHost", typeof(Base4Host), properties);

Here we're passing all our additional parameters as a
Dictionary inside our
IDictionary of additional properties....  this isn't
the most elegant implementation, but this is all code internal to
a single facility so it's not really important to me... and it
gets the job done just fine.

Read More


Abstractions...  mmmm... so sweet

...a post from Ayende on abstractions, and specifically a mention of the logging "abstraction" in Castle... it's an interesting thing, for the Seismic product I worked logging (via the same abstraction) into a product a year or more ago...  in the end we needed the ability to log contextual information (basically exposing features already existing in log4net at the time, but not available via the Castle ILogger interface) and so I ended up creating a new interface that was a superset of the existing abstraction, IExtendedLogger...

here's the devil... looks simple...

public interface IExtendedLogger : ILogger { void AddProperty(string key, object value); void RemoveProperty(string key); }

However... because we're being a good little abstraction "whore" we end up with a few more classes to support this new interface, and make the user experience more pleasurable:

Though I was reasonably pleased with the end result a year ago, that was probably a couple of hours work + some more time tweaking (once you include the time to code up that test fixtures) that would've been better spent building additional functionality into the product.

I have to admit the lure of a needless abstraction is ever present to me... I enjoy halving a class into an abstract and concrete implementation, and then extracting an interface is like the candy coating... prefixing the concrete implementation with "Default" makes it even seem like you've all but got people lining up to create their own versions!  Wow, isn't it powerful, flexible.. and all sorts of other words ending in "ul" or "ile".

....But in the end, needless is needless - and I haven't needed the flexibility gained from this abstraction so far... after a year... a whole year, that's pretty much like never... sure I had grand plans, but they never did come to fruition... and grand plans don't keep me fed - YAGNI strikes again.

About the only thing I find the needless abstractions do is in clarifying my thinking on what I do and don't need, or more importantly what I do and don't want people to do with my code.... it let's me define just what I want my "pit of success" behavior to be, albeit not the implementation... Perhaps some of this stuff is better reserved for throw away prototypes then production code.

I think the best book I've found for discouraging this "80's guitar solo" of is the Framework Design Guidelines... Though these abstractions do make it easy for me to maintain and grow my code (and the orthogonality of the design is generally good) it comes at the price of other people having difficulty learning my API through experimentation, and I fail to create a progressive framework... which after reading the aforementioned book, is something we all wan't to do.

I guess the final question is, do you reverse an abstraction that isn't required after such a long time...?  Or do you just avoid making the same mistake twice and live with the abstraction, assuming it's not hurting too many people - Is it worth lumping it with the rest of the "broken windows" in a project, or is that a little too brash?

Read More