IServiceLocator inject at constructor VS ServiceLocator's static member?

Sep 20, 2012 at 8:06 PM


In my WPF, I could not use constructor injected because of my ViewModel already derrived from other class.

Then I modified the helper code to following by using FullName ServiceLocator.

public class AutoNotificationObject : NotificationObject
        protected T Using() where T : class
            var handler = ServiceLocator.Current.GetInstance<T>();
            if (handler == null)
                throw new BusinessServicesException("Unable to resolve type with service locator: Type" + typeof(T).Name);
            return handler;




handler = ServiceLocator.Current.GetInstance<T>()public AuthorizedController

(IServiceLocator serviceLocator)
            this.serviceLocator = serviceLocator;

What differnt between the two

Sep 21, 2012 at 7:38 PM


As far as I know, the main difference is that you are obtaining the ServiceLocator from two different places.

When you obtain an instance of the ServiceLocator through constructor injection, you are receiving the instance registered in your dependency injection container. On the other hand, when you obtain an instance of the ServiceLocator through the ServiceLocator.Current property, you are receiving the instance referenced by the ServiceLocator class. As far as I know, as out of the box, both should hold the same ServiceLocator instance; therefore, it would be no difference in using one approach or the other.

However, if in your application, one of those references is changed (for example, you register a new instance of the ServiceLocator in your dependency injection container) the ServiceLocator.Current property will return a different instance that the one obtained through construction injection. As long as you don't manually change the instance of the ServiceLocator, you should be able to use both approaches without any problems.

As a side note, even if your view model derives from another class, you should be able to use constructor injection too. As far as I know, the only thing you should take into account when doing so is passing the corresponding parameters to the constructor of the base class.

I hope you find this useful,

Damian Cherubini

Sep 22, 2012 at 8:16 AM

Hi DCherubini,

Thank you very much.

Best Regards,