Service Locator with System.ComponentModel

posted @ Friday, April 14, 2006 12:03 PM

 

Javier mentioned from my previous post that it would be nice to be able to request an object directly from .NET, without a reliance on the Spring Framework. To a certain extent, this is provided in the System.ComponentModel and System.ComponentModel.Design namespaces. You can create a ServiceContainer and register services with it, then if you expose your ServiceContainer as an IServiceProvider, your client can then request services back from the container. It looks something like this:

IServiceContainer sc = new ServiceContainer();
sc.AddService(typeof(IDatabase), new Database());
// Add more services
IServiceProvider provider = sc as IServiceProvider;

Now, within another layer, assuming we have the IServiceProvider, I can do something like this:
IDatabase db = provider.GetService(typeof(IDatabase));