Wednesday, April 21, 2010

ServiceLocator.Current - calls the SetServiceLocator delegate everytime!

If like me you were under the impression that calling ServiceLocator.SetLocalProvider result would be cached when using static member ServiceLocator.Current then you'll be wrong.

I was surprised to find out that the ServiceLocator implementation passed to ServiceLocator.SetLocalProvider was created everytime I called ServiceLocator.Current.

I know I should always inject IServiceLocator into the ctor of the consumer types, but there are rare occasions that I need to use ServiceLocator.Current in static classes.

The implementation of ServiceLocator.Current looks like so:
public static IServiceLocator Current
{
get { return currentProvider(); }
}
currentProvider() is a good old fashioned delegate and looks like so:
public delegate IServiceLocator ServiceLocatorProvider();


So instead of doing this:
ServiceLocator.SetLocatorProvider(() => new WindsorServiceLocator(_container));
Do this:
IServiceLocator castle = new WindsorServiceLocator(_container);
ServiceLocator.SetLocatorProvider(() => castle);
You will get a load less garbage collections as a result.

If you have no idea what I am talking about in this post, please see the Common Service Locator by the p&p team at Microsoft here: http://commonservicelocator.codeplex.com/

1 comment:

Joe Humprey said...

nice thanks.

Joe