You might want to split up the initialization code for your IoC container in several classes. There might be several reasons to do so:
- You want to be able to easily replace just a subset of the components configured in your IoC container.
- You are building a class libary or a framework and you want to provide others a default initialization routine for the classes in your library/framework.
After some searching on the internet, it seems that Castle Windsor provides a nice way of doing this by using the IWindsorInstaller:
public class MyLibrariesWindsorInstaller: IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
//container.AddComponent<IMyInterface1, MyImplementation1>();
//…
}
}
You can find another example here.
Now you need to call the Windsor Installer from your main WindsorContainerBootstrapper. (A bootstrapper is a component that runs as part of the startup process to activate a more complex system.)
public class WindsorBootstrapper
{
private static IWindsorContainer _container;
public static void Initialize()
{
//initialize container with some IWinsorInstallers
container = new WindsorContainer(new XmlInterpreter());
//delegate initialzation to the configured Windsor Installers
_container.Install(_container.ResolveAll<IWindsorInstaller>());
}
}
In your app.config, you can now configure a list of IWindsorInstallers:
<Configuration>
<configSections>
<section name=”castle” type=”Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor” />
</configSections>
<castle>
<components>
<component id=”installer” service=”Castle.Windsor.IWindsorInstaller, Castle.Windsor” type=”MyLibrary.MyLibrariesWindsorInstaller, MyLibrary” />
<!– Configure more IWindsorInstallers here –>
</components>
</castle>
I find this a clean solution, which I found here. The only thing left to do is to call the WindsorBootstrapper.Initialize() method at application startup.
One last advice: be careful for registring components for the same interface in different IWindsorInstallers. Using this solution, there is still only one IoC container in your application…