I am using version 4 of MVVM Light for Windows 8; it includes SimpleIOC. In various examples I sometimes see code to request an object based on SimpleIoc... and sometimes it is based on ServiceLocator...
Examples include:
userToken = SimpleIoc.Default.GetInstance();
mainVM = ServiceLocator.Current.GetInstance();
What is the difference between using SimpleIoc.Default.GetInstance and ServiceLocator.Current.GetInstance?
If there is no difference, does ServiceLocator just let me to have an option to change my mind about what IOC library I want to use? Does ServiceLocator just provide an additional layer of abstraction that is irrelevant if I am satified with SimpleIoc; or, does ServiceLocator perform some other useful magic that is not obvious to we IOC novices?
Thanks for the insight!
In your ViewModelLocator class you probably have the following line of code:
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc
implements the IServiceLocator
interface, which means that the ServiceLocator
will use it as a DI source when invoked.
Edit:
OK, people want the "full fat and don't spare the cream" answer. Here we go!
ServiceLocator
is basically a shell. The code for Service locator is:
public static class ServiceLocator
{
private static ServiceLocatorProvider currentProvider;
public static IServiceLocator Current
{
get
{
return ServiceLocator.currentProvider();
}
}
public static void SetLocatorProvider(ServiceLocatorProvider newProvider)
{
ServiceLocator.currentProvider = newProvider;
}
}
Yup, that's it.
What's ServiceLocatorProvider
? It's a delegate that returns an object that implements IServiceLocator
.
SimpleIoc
Implements IServiceLocator
. So when we do:
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
We put our SimpleIoc
object into the ServiceLocator
. You can use either of these now because whether you call ServiceLocator.Current
or SimpleIoc.Default
you're returning the same object instance.
So, is there any difference between
userToken = SimpleIoc.Default.GetInstance();
mainVM = ServiceLocator.Current.GetInstance();
?
Nope. None. Both are singletons exposing a static property that is an implementation of IServiceLocator
. As mentioned above, you're returning the same instance of object that implements IServiceLocator
regardless of which you call.
The only reason why you might want to user ServiceLocator.Current.GetInstance()
rather than SimpleIoc.Default.GetInstance()
is that at some point in the future you may change DI containers and, if you use ServiceLocator
, you won't have to change your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With