Search code examples
c#dependency-injectioninversion-of-controlunity-container

UnityContainer.Resolve or ServiceLocator.GetInstance?


It could seem a stupid question because in my code everything is working, but I've registered a singleton this way with my Unity container _ambientContainer:

 _ambientContainer.RegisterType<Application.StateContext>(new ContainerControlledLifetimeManager());

In order to avoid to use my local field, I use:

get {
    return ServiceLocator.Current.GetInstance<Application.StateContext>();
}

inside my get property to get an instance of my object. This way I get always the same instance (Application.StateContext is still a singleton) or does GetInstance create a new one?

Is it better to use the local _ambientContainer field instead?

get {
    return _ambientContainer.Resolve<Application.StateContext>();
}

Thank you.


Solution

  • I'm assuming that the ServiceLocator type is from the CommonServiceLocator project, and that you're using the Unity adapter, in which case GetInstance invokes container.Resolve, so both lines are equivalent.

    You can view the source here - http://commonservicelocator.codeplex.com/wikipage?title=Unity%20Adapter&referringTitle=Home