views:

94

answers:

2

Hi everybody, I have a small toolkit which uses Unity DI plus EntLib Service Locator. The problem appears when a third party apps try to use the EntLib service locator. It looks like the EntLib Service Locator is singleton so when the third party app bootstrap its service locator, it wipes out the configuration of my service locator. The client creates the Service Locator in this way:

        container = new UnityContainer();
        locator = new UnityServiceLocator(Initialize());
        ServiceLocator.SetLocatorProvider(() => locator);

And it is used in this way:

ServiceLocator.Current.GetInstance<IService>("MyService");

Is there any way to manage two ServiceLocator or to register additional components in the service locator at runtime?

A: 

The only feasible solution I have found is to get the current IUnityContainer configured for the ServiceLocator and recycle it. In order to do that I used reflection in this way:

var locator = (UnityServiceLocator) ServiceLocator.Current;
var field = locator.GetType().GetField("container", BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
  var iocContainer = field.GetValue(ServiceLocator.Current) as IUnityContainer;
  if (iocContainer != null)
  {
   ConfigureContainer(iocContainer);
  }
}
+1  A: 

Since Unity container is registered within itself, you could get it and configure:

var container = ServiceLocator.Current.GetInstance<IUnityContainer>();
// do what you want with container
Anton
It works my MAN, thanks a ton!