UnityContainer.Resolve or ServiceLocator.GetInstance?

zero51 picture zero51 · Feb 16, 2012 · Viewed 30.9k times · Source

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.

Answer

Enrico Campidoglio picture Enrico Campidoglio · Feb 16, 2012

Passing around instances of the container to consumer classes isn't generally a good idea, since you are no longer guaranteed to have a single place in your application where components and services are being registered (known as the Composition Root).

Classes should state their dependencies in their public API, ideally by specifying them as constructor arguments, which the container will automatically provide an instance for whenever it's been asked to resolve a specific type (a process known as Autowiring).

Dependency Injection is usually the preferred choice but it isn't always applicable. In those cases using a Service Locator, like you're doing in your example, is the next best solution to decouple a class from its dependencies.

In conclusion, if Dependency Injection is not an option, I would avoid having my classes reference the container directly and instead have them access it through a Service Locator.