Monday 6 October 2014

Auto-Registration with StructureMap

When I want an IoC container I usually either use Unity or create my own really simple one. But I’ve been meaning to try out some of the alternatives, and so I decided to give StructureMap a try for my latest project.

I had two tasks to accomplish. The first was to tell it to use a particular concrete class (ConsoleLogger) as the implementer of my ILog interface. The second was to get it to scan the assembly and find all the implementers of my ICommand interface, without having to register each one explicitly.

As you’d expect. the first task is very simple to accomplish. You create a new Container, and then map the interface to the concrete implementer using a fluent API. Here I’ve said that my logger will be a singleton:

var container = new Container(x => 
    x.ForSingletonOf<ILog>().Use<ConsoleLogger>());
var logger = container.GetInstance<ILog>();

The second task is also straightforward to achieve with StructureMap. We ask StructureMap to scan the calling assembly, and add all types of ICommand. The one gotcha is that I had to make the ICommand interface and implementing classes public for it to detect them. Here’s the registration code:

var container = new Container(x =>
    {
        x.ForSingletonOf<ILog>().Use<ConsoleLogger>();
        x.Scan(a =>
           {
               a.TheCallingAssembly();
               a.AddAllTypesOf<ICommand>();
           });
   });

Now we can easily get hold of all the implementations of the ICommand interface like so:

var commands = container.GetAllInstances<ICommand>();

As you can see, it’s very straightforward. In fact there are ways with StructureMap to simplify things further by making use of conventions. So if you’re looking for an IoC that can do auto-registration, why not give StructureMap a try?

No comments: