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.
- Is using the constructor injection the right way to resolve this kind of dependency?
- Do I have to register my
BaseForm(and its’ derived types) in the container in order to create instances of them with resolved dependencies? Doesn’t that complicate everything? - Is it bad to use a static factory wrapped around a service locator?
- Unit-testing aside, will I really be punished because of using service locator anti-pattern?
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:
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: