Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 885
zero51 Avatar asked Feb 16 '12 09:02

zero51


2 Answers

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.

like image 126
Enrico Campidoglio Avatar answered Sep 22 '22 23:09

Enrico Campidoglio


Preferably you should avoid both ways of (ab)using your container.

The ServiceLocator is considered an anti-pattern in modern application architecture.

like image 30
Sebastian Weber Avatar answered Sep 18 '22 23:09

Sebastian Weber