问题
I am hearing people say you should not use Service Locator for your Dependency Injection. So how exactly do you inject the dependencies without relying on a service locator? I want to try out IoC containers, but don't want to land into an anti-pattern.
Should you just set everything up so there is one place where all classes always have a dependency chain to the deepest classes? (if I/that makes sense at all)
I isn't right to have all your code littered with dependencies on the IoC container of choice, is it?
So where do you "use" your the container (for rexolving)? And how do you get it to resolve everything, as deep as your code goes? Is it a part of designing everything the right way by using interfaces through every layer up till the front layer?
Or am I just missing a point?
Let me remind you that I just don't want to fall into an anti-pattern and need some tips / a heads up on it.
回答1:
Should you just set everything up so there is one place where all classes always have a dependency chain to the deepest classes? (if I/that makes sense at all)
Yes, this is called the composition root of your application, and it's where you would configure your IoC container and resolve your root type.
It isn't right to have all your code littered with dependencies on the IoC container of choice, is it?
Correct, it is better to not pass references to your IoC container around your types, as this will make them less reusable, and couple the types to the concept of IoC containers in general.
So where do you "use" your the container (for rexolving)? And how do you get it to resolve everything, as deep as your code goes? Is it a part of designing everything the right way by using interfaces through every layer up till the front layer?
You would use your container at your composition root, and anywhere in your code that needs to instantiate types (i.e. from factory types) via the container (usually for dependency chain support).
Many IoC containers can generate these factory types for you, so you only need to pass, e.g. IMyFactory
as a dependency, or in some IoC container's case, a Func<IMyService>
. That means that you don't need to create factory types that have a dependency on your IoC container.
In terms of using interfaces, the Dependency Inversion Principle states that you should depend on abstractions, not on concretions, so you will need to factor your code with this concept in mind if you wish to adopt dependency injection.
来源:https://stackoverflow.com/questions/5460564/how-to-use-dependency-injection-and-not-service-locator