Swapping Out Implementations of Interfaces (Castle Windsor)
by clayshannon
HTML
<h2>IoC Has No Point If You Don't Swap your Maps</h2>
<p>This tip is sort of an add-on to the article <a href="http://www.codeproject.com/Articles/710662/Simplest-Possible-ASP-NET-Web-API-Project-that-Imp">here</a></p>
<p>The whole point of Inversion of Control is so that you can pass different concrete implementations of an interface to a Controller that expects a class that implements a specific interface, but does not specify or even care what
precise class it receives.</p>
<p>To specify which implementing class is used, you might write code such as this:</p>
<pre>
public class RepositoriesInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For<IDuckbilledPlatypusRepository>().ImplementedBy<DuckbilledPlatypusRepository>().LifestylePerWebRequest(),
Component.For<ISiberianTigerRepository>().ImplementedBy<SiberianTigerRepository>().LifestylePerWebRequest(),
Component.For<IBottlenosedDolphinRepository>().ImplementedBy<BottlenosedDolphinRepository>().LifestylePerWebRequest(),
Component.For<IPterodactylRepository>().ImplementedBy<PterodactylRepository>().LifestylePerWebRequest(),
Component.For<IButterflyRepository>().ImplementedBy<ButterflyRepository>().LifestylePerWebRequest());
}
}
</pre>
<p>But wait a minute -- "Whoa there, pard!" you might be saying. Isn't that a bit verbose? It's true there are other ways -- three, in fact - that you can map your interfaces (that is to say, the interfaces that are represented as argument types in your Controller's constructors): You can use XML files (which have the advantage of late binding), you can use auto-wiring or auto-registering, allowing the compiler to use reflection and register all interfaces you tell it to find, or you can do it in code, as shown above. The first way (XML) is largely considered...