Search code examples
c#wpfmvvmnullreferenceexceptionservice-locator

can ServiceLocator.Current.GetInstance return null?


I have this piece of code (or similar) in many of our views:

private IEventAggregator eventAggregator;

Constructor()
{
    eventAggregator = ServiceLocator.Current.GetInstance<IEventAggregator>();
    ...
}

I read from this post that ServiceLocator.Current can throw NullReferenceException (bad thing on a constructor) but I was wondering if the GetInstance<>() method can return null (or some other inconsistent object) making eventAggregator dangerous to use later in other methods.

NOTE: I'm quite new to MVVM and WPF


Solution

  • If the servicelocator is null, then there is probably something not correctly setup for unity. under normal circumstances it shouldnt be an issue imho.

    having said that, i tend to use a slightly different way to get to the servicelocator.

    for instance, if i have a class called MyClass i will use unity dependency injection to pass the servicelocator in ( also referred to as the container in unity ). And I tend to use the Resolve functionality of unity rather than GetInstance, but they are the same.

    There is also talk that the servicelocator is an antipattern, but i dont buy into that line of thinking. http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx

    example

    public MyClass(IUnityContainer container)
    {
        var ea = container.Resolve<IEventAggregator>();
    }