rol
rol

Reputation: 51

Questions about implementation of service locator

I need your help, I know that the service locator is not one of the best options, but taking into account the implementation of it.

The most correct would be to have a Locator class in each layer, this class would be responsible for resolving the dependencies of that specific layer ?

Example: Business Layer has its own service locator class that only solves the dependencies of this layer, Data Access Layer has its own locator too.

If not the best option, what do you advise?

In advance, thank you.

Upvotes: 1

Views: 219

Answers (1)

Steven
Steven

Reputation: 172646

You should not have one service locator per layer. There should only be one Composition Root in your entire application and that would be the only place where you resolve object graphs. You should not break things up at the layers.

For instance, an MVC HomeController might take a dependency on an IRepository<T> (DAL layer) or ICommandHandler<T> (business layer) and these should simply be dependencies in the HomController's constructor. Letting the HomeController call into a BusinessLayerServiceLocator.GetInstance would cause problems when trying to unit test that HomeController. And it would make wiring the application much harder.

However, this doesn't mean that you should place the code that wires a layer inside the startup project. For instance, you can place the code that wires all business classes inside the business layer assembly or an assembly that is placed 'on top of' the business layer assembly. You should however only do this if this business layer is shared between multiple applications (both a MVC and WCF project for instance). And when you do this, you still should not have a service locator inside the business layer. Instead you should pass a container instance to the Bootstrap method of the business layer. This way it can configure that container instance, but the end application keeps the reference and keeps control.

Upvotes: 1

Related Questions