In a previous post I talked about how you can setup Contextual Binding and Profiles with StructureMap 2.5. However since this post was published, the way you can configure Profiles has changed. Because of this I thought I would post a follow-up on how to do this. I also wanted to give a little more complex example to help illustrate the point.
In our application at work we have a API which has multiple 'processors’ and depending on which processor you need the dependences may change. Because all of these processors implement the same interfaces (contract) as do all their dependancies. I wanted to setup profiles in order to easily manage grabbing the correct profile from ObjectFactory. One other thing is that each processor is its own dll which means it has its own IoC registry for StructureMap.
Why don't we skip all the blah, blah, blah and start looking at code.
This is my IoC registration bootstrap. this is what is responsible for calling the various registries for StructureMap
public class IoCBootstrap
{
public static void SetupRegistriesForIoC()
{
ObjectFactory.Initialize(
scanner =>
{
scanner.AddRegistry( new IoCCommonRegistry() );
scanner.AddRegistry( new IoCOutboundPipelineRegistry() );
scanner.AddRegistry( new IoCOutboundAdmissionRegistry() );
}
);
}
}
Below is the implementation of one of my registries, the one which actually setsup the profile
public class IoCOutboundAdmissionRegistry: Registry
{
protected override void configure()
{
CreateProfile( ProcessorProfiles.OutboundAdmission,
x =>
{
x.For<IMessageProcessor>().UseConcreteType<AdmissionProcessor>();
x.For<IMessagePackager>().UseConcreteType<AdmissionMessagePackager>();
x.For<IMessageValidator>().UseConcreteType<AdmissionMessageValidator>();
x.For<IMessageRepository>().UseConcreteType<AdmissionRepository>();
}
);
}
}
Now that we have created our profile, how do we set our profile for use
// set the profile
ObjectFactory.Profile = ProcessorProfiles.OutboundAdmission;
// get the instance as normal
ObjectFactory.GetInstance<IMessageProcessor>()
As you can see using the new fluent configuration syntax does not really change anything too much, but it does add a little wrinkle.
Till next time,
Posted
01-07-2009 11:31 AM
by
Derik Whittaker