I am writing a library that will provide a collection of public types to its consumers.
I want to make the types from this library dependent on injection. This means that each class must have a constructor through which you can specify each individual dependency of the initialized object. I also want the library to adhere to the convention on the principle of configuration. This means that if the consumer wants the default behavior, he can use the constructor without parameters, and the object will somehow build the dependencies for himself.
In the example (C #):
public class Samurai { private readonly IWeapon _weapon;
My first solution would be to use a service locator pattern.
The code will look like this:
... public Samurai() { _weapon = ServiceLocator.Instance.Get<IWeapon>(); } ...
I have a problem with this. The service locator is marked as anti-pattern ( link ), and I completely agree with these arguments. On the other hand, Martin Fowler advocates the use of the service locator template in this situation (library projects) ( link ). I want to be careful and eliminate the possible need to rewrite the library after it discovers that the service locator was really a bad idea.
So in conclusion - do you think the service locator is good in this scenario? Should I solve my problem in a completely different way? Any thought is welcome ...
Tomas source share