The First Spec You Should Write When Using Castle

Thought this might be useful. On a new project where you're using the Castle Windsor container for Dependency Injection, this is a handy spec to have:

[TestFixture]
public class When_starting_the_application : Spec
{
    [Test]
    public void verify_Castle_Windsor_mappings_are_correct()
    {
        IWindsorContainer container = new WindsorContainer("castle.xml");
        foreach (IHandler handler in container.Kernel.GetAssignableHandlers(typeof(object)))
        {
            container.Resolve(handler.ComponentModel.Service);
        }
    }
}

It doesn't guarantee that someone missed adding something to your configuration, but this way anytime someone adds a type to the configuration this will verify the mapping is right. Very often I move things around in the domain into different namespaces and forget to update Castle. I supposed you *could* use reflection on your assembly as another test and verify the mapping is there, but not every type in the system is going to be dependency injected so that's probably not feasible.

Thanks to the Castle guys for helping me get the simplest syntax going for this.

5 Comments

  • I know this has nothing to do with the subject of your post, but I'm curious, is "Spec" your own base class?

  • @Greg: You can find an example of the Spec class here on Dave Laribee's blog: http://codebetter.com/blogs/david_laribee/archive/2007/12/17/approaching-bdd.aspx

  • Thanks for sharing.

  • Thanks for sharing this.
    BTW, for my container I had to add two lines before calling Resolve():

    if (handler.ComponentModel.Service.IsGenericType)
    continue;

    This will skip components with generic arguments, like IRepository. Since we don't know the argument at this moment, Resolve() will throw.

  • Here's a dumb question. We keep Windsor Config with the app.config file. I added this spec (awesome BTW, wish I'd thought of that!) and pointed it to the application under test's config file, but it errors out because of the other sections of the config file.

    The easy answer is to separate the Windsor configuration out from the app.config and divorce the two. I am not quite ready to do that if there is an easy way to get Windsor to only use the section of the config file that I tell it to. This is easy with your local config, but it doesn't appear to be as easy when pointing off to an XML file somewhere else.

    I tried the XMLInterpreter (among a couple of other things), but perhaps I am missing something somewhere.

    Any ideas?

Comments have been disabled for this content.