ServiceLocator is throwing NullReferenceException ?

Topics: Enterprise Library Core, General discussion, Policy Injection Application Block
Nov 20, 2012 at 3:34 AM

I have below functions to create my local unity container. But I always gets NullReference exception when , the program point reaches ServiceLocator..why is that ?

   var config = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

            try
            {
                if (ServiceLocator.Current != null) ----> This is where we get ServiceLocator is null
               
                {
                    var x = ServiceLocator.Current.GetInstance();
                 

                    if (config.Containers.Count > 0)
                    {
                        config.Configure(x);
                    }

                    return;
                }
            }
            catch (NullReferenceException ex)
           
            {
              
                int i = 1;
            }

Nov 20, 2012 at 4:58 AM

I'm not 100% sure what you are trying to do but if you are trying to load Unity Configuration you can use the following:

using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity;

//...

IUnityContainer container = new UnityContainer();
container.LoadConfiguration();

If you want to use ServiceLocator directly instead of UnityContainer then you can use UnityServiceLocator implementation:

IUnityContainer container = new UnityContainer();
container.LoadConfiguration();
UnityServiceLocator locator = new UnityServiceLocator(container);

ServiceLocator.SetLocatorProvider(() => locator);

try
{
    if (ServiceLocator.Current != null) // true!
    {
        var x = ServiceLocator.Current.GetInstance();                 
        return;
    }
}
catch (NullReferenceException ex)            
{
    int i = 1;
}

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com