Archive for the ‘StructureMap’ Category

Advanced StructureMap: Diagnosing problems

So you’ve set up StructureMap, got all your registries in a row, go to run the application, and you’re greeted by a rather unfortunate message:

StructureMap.StructureMapException : StructureMap Exception Code:  202
No Default Instance defined for PluginFamily

That’s just one of the issues we can run into.  If you’re doing more advanced things like nested containers, lifecycle management, external plugin folders for dynamic loading, you’re bound to run into binding and other bugs at runtime.  One of the things I like about StructureMap over other containers I’ve tried is the level of support for diagnosis, configuration validation, and testing.

When using any configuration tool, whether it’s IoC container configuration, Web.config or other persistent mechanism for application configuration, you will run into problems.  The first step to diagnosing issues is to write tests.

Testing StructureMap configuration

The easiest way to test your StructureMap configuration is to use the ObjectFactory.AssertConfigurationIsValid() method in a test:

ObjectFactory.Initialize(init =>
{
    init.AddRegistry<HandlerRegistry>();
});

ObjectFactory.AssertConfigurationIsValid();

Internally, StructureMap will loop through all of your registered instances and try to instantiate them.  This can catch 99% of your registration problems, as you might have forgotten a registry somewhere or an instance isn’t defined for something.  The key to remember is that StructureMap can only validate plugin types it knows about.  Just like AutoMapper, it can’t divine all the ways you’re using ObjectFactory.GetInstance() in your codebase.  So typically, AssertConfigurationIsValid() is our first line of defense.

The next way to test is for specific registries.  Suppose we’ve defined some custom registry:

    public class HandlerRegistry : Registry
    {
        public HandlerRegistry()
        {
            Scan(cfg =>
            {
                // etc

If we have some custom registration logic (very likely), then we can then test that registry in isolation from the rest of our configuration.  This is what I do when I’m doing lots of meta-programming to hook up open generic types of things, and in general building highly de-coupled, SOLID stuff ;)

Side note: things like ConnectImplementationsToTypesClosing() should be built in to every IoC container registration.  It’s one of the things I can point to on our current project and say, “that enabled some of our success”.  If we had to register/build these things manually, we wouldn’t have tried to build the architecture we wound up doing, which let us scale our development very easily.

To test a single registry in isolation, you simply need a Container object:

[Test]
public void Should_connect_delete_handler_by_registry()
{
    var container = new Container(new HandlerRegistry());

    var handler = container.GetInstance<IHandler<DeleteEntityCommand<Customer>>>();

    handler.ShouldBeInstanceOf<DeleteEntityCommandHandler<Customer>>();
}

I instantiate a new Container object, but I pass in the instance of my custom registry.  From there, I can then use the Container directly to get an instance.  With registry-specific tests, I can ensure some of my more complex (and insanely powerful) registration is hooked up correctly.  If you’re using a container beyond just hooking up Foo to IFoo, I highly recommend doing registry-specific testing.  It’s much easier to test-drive a registry in isolation than it is to try and catch things at runtime.

Popping open the hood

Sometimes, you’ll get a “No default instance defined” exception, and in those cases, it’s best to just pop open the hood of StructureMap, and see what do I have?

ObjectFactory.Initialize(init =>
{
    init.AddRegistry<HandlerRegistry>();
});

Debug.WriteLine(ObjectFactory.WhatDoIHave());

Wow, there’s a method, “WhatDoIHave()”.  It’s on both ObjectFactory, and Container (ObjectFactory is merely a wrapper around a Container object).  This method returns a nicely formatting string showing everything in our container:

=======================================================================================
PluginType
---------------------------------------------------------------------------------------
IHandler`1<DeleteEntityCommand`1<TEntity>> (IHandler`1<DeleteEntityCommand`1<TEntity>>)
Scoped as:  String

Well, there’s a lot more information here, but it basically lists out each registered plugin type and configured instances.  If you see a blank in the configured instances, that’s something that is registered, but doesn’t have a concrete instance.

Lifecycle issues

One of the major features of modern IoC containers is the ability to provide lifecycle management.  This means that we can use our container to control the lifetime of our instance, singleton, per-request, HttpContext, etc. etc.  That’s an extremely powerful tool, but one that cuts very, very deep if it’s not hooked up right.  Unfortunately, it’s also not one that’s easy or even possible to unit test in some cases.  Lifecycle configuration in your container is application behavior, and like things such as web.config, config stored in DB, external XML configuration etc. can only really be verified with the whole app up and going.

Before understanding lifecycle issues, it’s critical that you fully understand the lifecycle of the code calling ObjectFactory/Container.GetInstance().  Whenever I’ve had problems with lifecycle, it’s because I just misunderstood, didn’t understand, or was completely ignorant of the thread lifecycle of whatever was trying to build my lifecycle-configured instance.  My WCF understanding was wrong, and my hand-coded lifecycle management totally screwed up things that were found only after it went to production.  It’s really no different than if you wanted to start storing things in a static cache, but now need to deal with multiple threads, who gets what instance, and so on.

So back to debugging lifecycle issues.  In practice, when things don’t work, I do a healthy dose of logging + GetHashCode() to put out messages showing exactly what gets what instance.  About a year ago, I had to debug a gnarly lifecycle problem.  One thing I found is that it gets much, much harder if you’re instantiating things yourself and get away from DI however, as some old code we had put too many moving parts into play, making it that much harder to understand what came from where.  So my preference is to push as much instantiation into the container as you can.  That said, it’s not for everyone, so you’ll have to decide how much magic juju you’re comfortable with.

That aside, here’s an example of what I like to do:

public class DeleteCustomerCommandHandler : IHandler<DeleteCustomerCommand>
{
    private readonly ICustomerRepository _customerRepository;

    public DeleteCustomerCommandHandler(ICustomerRepository customerRepository)
    {
        Debug.WriteLine("Received instance of ICustomerRepository in DeleteCustomerCommandHandler: "
            + customerRepository.GetHashCode());
        _customerRepository = customerRepository;
    }

It’s a primitive tool, but I use it to both build and debug lifecycle issues.  It could be Debug, or it could be any logger or whatever to be able to see basically the instance ID from GetHashCode().  I would see log messages of mismatched hash codes, things being instantiated more than I thought they should, and so on.  Whenever I had lifecycle issues, it was because the instantiator had one lifecycle, and the plugin type had another conflicting lifecycle configuration.

Now, this is just my way of debugging lifecycle issues.  If there’s some other ways of doing so, I’d love to hear about it.  I’m pretty sure this could be done also with AOP/profiling tools too.

Wrapping it up

IoC containers are magic juju boxes.  But they don’t have to be, if you have the right tools to test and diagnose problems.  If you do wind up drinking the container kool-aid, be prepared to have something go wrong at some time.  Like other sharp tools, it can really destroy a lot of time if you don’t have a good plan for diagnosing these issues.  And if nothing works, you can always go to the mailing list of your respected project (as long as your project is active and OSS for the most part) for some free help.

Kick It on DotNetKicks.com

Advanced StructureMap: custom registration conventions for partially closed types

A while back, I highlighted an issue we ran into where I had basically partially closed generic types.  A common pattern in message- and command-based architectures is the concept of a handler for a message:

public interface IHandler<TEvent>
{
    void Handle(TEvent args);
}

It’s a pattern with many names, but the basic concept is to separate the execution of a command from the representation of a command.  We use it with our ActionResult objects, command messages and lots of other places where creating a parameter object separate from the method using the parameter object provides a great benefit.  But as we used this pattern more and more, we would start to see duplication around certain types of commands.  For example, we might have a command to delete a customer:

public class DeleteCustomerCommand
{
    public DeleteCustomerCommand(Customer customer)
    {
        Customer = customer;
    }

    public Customer Customer { get; private set; }
}

And the implementation is fairly straightforward:

public class DeleteCustomerCommandHandler : IHandler<DeleteCustomerCommand>
{
    private readonly ICustomerRepository _customerRepository;

    public DeleteCustomerCommandHandler(ICustomerRepository customerRepository)
    {
        _customerRepository = customerRepository;
    }

    public void Handle(DeleteCustomerCommand args)
    {
        _customerRepository.Delete(args.Customer);
    }
}

That’s all fine and dandy, but now I have to create another handler for every. single. entity. type. in. the. world.  That’s duplication I’d like to avoid, especially since it provides absolutely zero value (other than extra code I have to maintain).  Instead, I’d like to define a generalized command:

public class DeleteCommand<TEntity>
{
    public DeleteCommand(TEntity entity)
    {
        Entity = entity;
    }

    public TEntity Entity { get; private set; }
}

Now I only need to define a generic handler for this command:

public class DeleteEntityCommandHandler<TEntity> : IHandler<DeleteEntityCommand<TEntity>>
{
    private readonly IRepository<TEntity> _repository;

    public DeleteEntityCommandHandler(IRepository<TEntity> repository)
    {
        _repository = repository;
    }

    public void Handle(DeleteEntityCommand<TEntity> args)
    {
        _repository.Delete(args.Entity);
    }
}

Up to this point, I’ve shown nothing new that I didn’t already have in that previous open generics post.  The trick now is to hook up the right handler to the right message.  In the last StructureMap post, I showed how to hook up IHandler<T> to the concrete implementation.  But in this case, I don’t have a concrete implementation.  I will request an IHandler<DeleteEntityCommand<Customer>> or Order or whatever, and I need to wire up a new concrete type, DeleteEntityCommandHandler<Customer> (or Order or whatever).

Because I have the issue where I don’t know the concrete type until it’s requested, I need to tell my IoC Container of choice (StructureMap) how to handle these requests.

Creating a custom registration convention

Quick note on StructureMap – internally, concrete types are matched up to requested types through configuration.  StructureMap does a great job at reducing the amount of configuration through registration conventions, registries and configuration, but I still have to match up every concrete service type to a requested type.  StructureMap (I believe) doesn’t let you wait until a type is requested to find its implementation, it already needs to know it beforehand.

So how does that affect me?  For one, I only have one implementation, but it’s generic.  I could literally have as many closed generic implementations as there are entities in my system, because each will get its own (correct) repository implementation.

The interesting thing about the “ConnectImplementationsToTypesClosing” method I highlighted last time is that this is actually just a helper method to use an existing IRegistrationConvention (previously TypeScanner in 2.5.3 and earlier).  The IRegistrationConvention is a fairly simple interface:

public interface IRegistrationConvention
{
    void Process(Type type, Registry registry);
}

During the scanning process, StructureMap will call any convention I add, passing in the type to check and a Registry object.  If the type seems interesting to me, I’ll register the interface and implementation in the Registry object.  So what do we need to do here?

Basically, we want to look for all subclasses of Entity, and register the delete command handler for that entity type.  To do so, it will require some open generics magic:

public class DeleteCommandRegistrationConvention : IRegistrationConvention
{
    private static readonly Type _openDeleteCommandType = typeof(DeleteEntityCommand<>);
    private static readonly Type _openHandlerInterfaceType = typeof(IHandler<>);
    private static readonly Type _openDeleteCommandHandlerType = typeof(DeleteEntityCommandHandler<>);

    public void Process(Type type, Registry registry)
    {
        if (!type.IsAbstract && typeof(Entity).IsAssignableFrom(type))
        {
            Type closedDeleteCommandType = _openDeleteCommandType.MakeGenericType(type);
            Type closedHandlerInterfaceType = _openHandlerInterfaceType.MakeGenericType(closedDeleteCommandType);
            Type closedDeleteCommandHandlerType = _openDeleteCommandHandlerType.MakeGenericType(type);

            registry.For(closedHandlerInterfaceType).Use(closedDeleteCommandHandlerType);
        }
    }
}

First, I create some static members for all the open generic types I care about.  Notably, the open command type, the open handler interface type, and the open command handler type.  What I want to do is hook up all requests for IHandler<DeleteEntityCommand<Foo>> to the closed type DeleteEntityCommandHandler<Foo>.  In the Process method, I look for all non-abstract subclasses of Entity, and close all the open types.  Finally, I instruct StructureMap to wire up the closed interface (IHandler<>) to the closed implementation (DeleteEntityCommandHandler<>).

Hooking up our custom registration convention

In the last article, I hooked up the IHandler implementations.  We’ll need to keep that, but additionally register not only the convention we created, but the repositories we use as part of the concrete handler:

public class HandlerRegistry : Registry
{
    public HandlerRegistry()
    {
        Scan(cfg =>
        {
            cfg.TheCallingAssembly();
            cfg.IncludeNamespaceContainingType<OrderCanceledEvent>();
            cfg.ConnectImplementationsToTypesClosing(typeof(IHandler<>));
            cfg.ConnectImplementationsToTypesClosing(typeof(IRepository<>));

            cfg.Convention<DeleteCommandRegistrationConvention>();
            cfg.WithDefaultConventions();
        });
    }
}

To add a convention, I use the “Convention” method and pass in the convention type.  To hook up the repositories, I add both the line to connect implementations for IRepository<>, as well as the “WithDefaultConventions”, which matches up ICustomerRepository to CustomerRepository.  I don’t need that last part for this example, but is almost always included in most of my scanning operations.

With this in place, my test now passes:

[Test]
public void Should_connect_delete_handler()
{
    ObjectFactory.Initialize(init =>
    {
        init.AddRegistry<HandlerRegistry>();
    });

    ObjectFactory.AssertConfigurationIsValid();

    var handler = ObjectFactory.GetInstance<IHandler<DeleteEntityCommand<Customer>>>();

    handler.ShouldBeInstanceOf<DeleteEntityCommandHandler<Customer>>();
}

It’s a lot of angle-bracket tax, but you never actually see this many angle-brackets.  My application will push commands out, and a rather brainless command processor will locate handlers for the command, and execute them.  With StructureMap (and IoC in general), I can start to really reduce duplication when that duplication is around the type varying, by prudent application of generics.  Here, I’m not using generics for type safety, but to reinforce the DRY principle.

With a powerful IoC tool, I don’t have to compromise on my command processing design just because I have complex message/handler shapes.  Instead, the command processor stays simple, and lets my IoC registration encapsulate all of the wiring.

Kick It on DotNetKicks.com

Advanced StructureMap: connecting implementations to open generic types

One pattern we’re starting to see more and more is the idea of connecting messages to handlers.  These messages might be domain command messages, ActionResult messages, and more.  Beyond messaging implementations, we start to see a more basic pattern start to emerge.  We have some interface describing a contract that happens to be generic:

public interface IFooService<T>
{
    void DoSomething(int value, T foo);
}

Now, if we weren’t doing IoC, and we needed a specific FooService for some type T, we’d have to know which type to get.  But you might start to see situations where you need an IFooService<T>, but you don’t really care about the T specifically:

public class SomethingThatUsesFoo<T>
{
    private readonly IFooService<T> _service;

    public SomethingThatUsesFoo(IFooService<T> service)
    {
        _service = service;
    }

    public void SomethingSpecific(T value)
    {
        _service.DoSomething(4, value);
    }
}

As you start to build more and more generic components, building out common infrastructure components, you’ll start to build more common services like these, that coordinate between a messages and their handlers.  In most cases like these, we’re not using generics for type safety, but rather for metadata to match up input types to output services.  A more concrete example on a real project looks like this:

public interface IHandler<TEvent>
{
    void Handle(TEvent args);
}

This is an interface for domain events, where we’ll have handlers like:

public class OrderCanceledEvent
    : IHandler<OrderCanceledMessage>
{
    public void Handle(OrderCanceledMessage args)
    {
        // send an email or something
    }
}

Now the trick is, how do we instruct our Inversion of Control container to locate the right handler for the right event?  If you’re using StructureMap, it’s dirt, dirt simple.

Configuring StructureMap

Because we’re using StructureMap, we’ll be using a custom Registry to do our configuration.  To connect implementations, we want to make sure that any time we ask StructureMap for an IHandler<T>, it finds the concrete type of handler T.  In the above example, our common message routing code will ask for an IHandler<OrderCanceledMessage>, and the type located needs to be OrderCanceledEvent, because OrderCanceledEvent implements the IHandler<OrderCanceledMessage>.

Our Registry winds up being very simple:

public class HandlerRegistry : Registry
{
    public HandlerRegistry()
    {
        Scan(cfg =>
        {
            cfg.TheCallingAssembly();
            cfg.IncludeNamespaceContainingType<OrderCanceledEvent>();
            cfg.ConnectImplementationsToTypesClosing(typeof(IHandler<>));
        });
    }
}

To connect implementations to our open generic type of IHandler<T>, we use the ConnectImplementationsToTypesClosing method.  The other two are just directions telling StructureMap where to look for my handlers.  Typically, my registration code lives in the same assembly as the actual interfaces I’m registering, but you can also register by name.

But that’s it!  Very simple, one line to connect all of the handlers to their implementations.  I can verify this with a simple test:

[Test]
public void Should_connect_types()
{
    ObjectFactory.Initialize(init =>
    {
        init.AddRegistry<HandlerRegistry>();
    });

    ObjectFactory.AssertConfigurationIsValid();

    Debug.WriteLine(ObjectFactory.WhatDoIHave());

    var handler = ObjectFactory.GetInstance<IHandler<OrderCanceledMessage>>();

    handler.ShouldBeInstanceOf<OrderCanceledEvent>();
}

This test passes, and all is well in IoC land.

Embracing the container

At some point, users of IoC learn to stop caring and love the bomb container.  In our system, we have no less than ten usages of this method, meaning we have refactored a lot of common plumbing and coordinators into our infrastructure layer.  We can easily add new handlers, mappers, repositories, providers, commands, builders, invokers, etc., all with one line of configuration for each open type (NOT one per derived type/implementation).  It certainly opens the doors to new possibilities of separation of concerns between different pieces, we just happen to lean on the type system to route our information around.

Something to note here is that at no time did I need to describe the implementors.  StructureMap’s scanner merely found implementations of types closing IHandler<T>, and connected that concrete type to the requested type of IHandler<SpecificType>.  I’ve taken a look at the other containers, and frankly, I haven’t found any that match this level of simplicity in configuration.  But I’m not an expert on the other containers, so I’d love to be proven wrong!

Regardless, I absolutely love this pattern of usage in IoC.  It promotes a level of SOLID design that’s pretty tough to beat.  When folks talk about IoC only being useful in large or complex projects, I just don’t understand it.  Usages like this give me Separation of Concerns from the get-go, at almost zero cost.  If only other frameworks were built with this in mind

Kick It on DotNetKicks.com