Reputation: 1669
Suppose I have a BaseForm
which depends on an ILogger
or IResourceManager
or something like that. Currently it resolves the correct implementation of the required service using the service locator which I know is an anti-pattern.
BaseForm
(and its' derived types) in the container in order to create instances of them with resolved dependencies? Doesn't that complicate everything?Sorry about asking many questions at once. I've read the following SO questions and many others but reading them only added to my confusion:
Upvotes: 4
Views: 2215
Reputation: 172855
If possible, you should always go with dependency injection, since it has a few clear strength. With UI technologies however, it is not always possible to use dependency injection, since some UI technologies (in .NET space, Win Forms and Web Forms, for instance) only allow your UI classes (forms, pages, controls, etc) to have a default constructor. In that case you will have to fall back to something else, which is service locator.
In that case I can give you the following advice:
Besides unit testing, there are two other important arguments against the use of the Service Locator, which are given by Mark Seemann in his famous blog post Service Locator is an Anti-Pattern:
Upvotes: 8