IServiceLocator a step toward IoC container / Service locator detente

Today we launched an exciting project on CodePlex, namely the Common Service Locator library. What is it? It's a shared interface that applications and frameworks can reference in order to leverage IoC containers / service location mechanisms without taking hard dependencies.

The dominoes all fell like this. It all started with Jeremy Miller's post. This then spurred on Ayende to send an email to a bunch of folks including many of the leading IoC container authors including Chris Tavares who wrote Unity, and myself (no I haven't written an IoC container yet :)) Next thing you know we're all designing the new library over email over a period of several weeks.

You can read more on this at Chris's post here.

If you download the library you'll find the following interface.

 namespace Microsoft.Practices.ServiceLocation
 {
     public interface IServiceLocator : IServiceProvider
     {
         object GetInstance(Type serviceType);
         object GetInstance(Type serviceType, string key);
         IEnumerable<object> GetAllInstances(Type serviceType);
  
         TService GetInstance<TService>();
         TService GetInstance<TService>(string key);
         IEnumerable<TService> GetAllInstances<TService>();
     }
 }

You'll also find a static ServiceLocator class that exposes an ambient (current) container. This provides a convenient way for frameworks to grab access to the current locator. It allows you to provide a delegate which will get invoked to retrieve the current locator.

 namespace Microsoft.Practices.ServiceLocation
 {
     public static class ServiceLocator
     {
         private static ServiceLocatorProvider currentProvider;
  
         public static IServiceLocator Current
         {
             get { return currentProvider(); }
         }
  
         public static void SetLocatorProvider(ServiceLocatorProvider newProvider)
         {
             currentProvider = newProvider;
         }
     }
 }

So how many people did it take to design such an API? Well let's see eight (no this is not a bad joke). The beauty is that those people represent a collaborative design effort both within and external to Microsoft. Yes, we all reached an agreement!

In addition to the this interface, you'll find several adapters for IoC containers available with more on the way. I'll be adding one for MEF (which is a locator) to that list shortly.

Also you'll find a suite of unit tests you can use to validate that an adapter meets the functional requirements of the locator interface. We can thank Oren for that contribution :)

Our hope is that this interface will encourage products and frameworks to start leveraging IoC / Service location now that we're removing the need to depend hardly on a specific one. The community can make this hope a reality ;-)