Previously in this series:
WhoDaBest - Post 1, WhoDaBest - Post 2, WhoDaBest - Post 3, WhoDaBest - Post 4
I think I've been spending more time running and working out than doing dev lately. I made an attempt to get refocused for a bit today and accomplished a few things. First of all, I just don't like the term "Foundation", so I renamed my WhoDaBest.Foundation project to WhoDaBest.Commons.
I was also trying to think of the best way to set up my IOC container today, for which I have chosen Castle Windsor. It seems to be the IOC container du jour for .Net, although I've previously only used Spring. Seems pretty straight-forward to set up. I don't want my classes using the WindsorContainer class outright however. I'd like there to be at least a little abstraction from this class. So I've made my own IContainer interface. It has one simple method right now: "GetInstance". This is demonstrated below:
/// <summary>
/// Interface to be implemented by any IOC container used in the application.
/// </summary>
public interface IContainer
{
/// <summary>
/// Gets an instance of the specified object from the IOC container.
/// </summary>
/// <typeparam name="T">Type of the object to return.</typeparam>
/// <returns>An instance of the specified object.</returns>
T GetInstance<T>();
}
I then have a CastleWindsorContainer that implements this interface and wraps Castle Windsor. Basically this amounts to having a common adapter for each IOC I may implement, however unlikely that I will switch to Spring or Structuremap, etc...
The other issue with this approach is: I will use my IOC container to "spring" up my objects, but how do you create your IOC container? I'm jumping off the low board right now by creating a locator called ContainerLocator. The locator would typically be a singleton, but for the time being, I just have a static method called, GetContainer and another called GetInstance which gets the container and also provides the instance of the requested object. I imagine there's some better way to handle this, but just not sure what it might be at the moment.
/// <summary>
/// Static locator class to allow easy access to the IOC container.
/// </summary>
public class ContainerLocator
{
/// <summary>
/// Gets an instance of the specified object from the IOC container.
/// </summary>
/// <typeparam name="T">Type of the object to return.</typeparam>
/// <returns>An instance of the specified object.</returns>
public static T GetInstance<T>()
{
IContainer container = GetContainer();
return container.GetInstance<T>();
}
/// <summary>
/// Gets the current IOC container.
/// </summary>
/// <returns>The current IOC container.</returns>
public static IContainer GetContainer()
{
return new CastleWindsorContainer();
}
}