What is the difference between using the Service Locator anti-pattern and using the Castle Windsor container?\" [closed]

℡╲_俬逩灬. 提交于 2019-11-28 09:23:48
Mark Seemann

Funny you should ask to have it explained like you were six years old; here's an explanation like you were five years old :)

everywhere I look I see a push in the direction of containers such as Castle Windsor

Frankly, I think the reason for that is that most people actually don't understand what Dependency Injection is, which means that instead of grasping the concept of Inversion of Control, they go looking for a replacement for the new keyword they're already used to. Then they find a DI Container and (mis)use it as a Service Locator. Unfortunately, that's very easy to do.

This is the reason why, in my book, I explain all the DI concepts without coupling the explanation to any single DI Container. That's actually the majority of the book.

Service Locator and Dependency Injection are two fundamentally different attempts at achieving loose coupling. Service Locator has many disadvantages, and offers no advantages not also offered by DI. This is why I think it's safe to call Service Locator an anti-pattern.

You don't need a DI Container to use DI; in fact, I would say that unless you take a rather sophisticated approach, it's probably better to avoid one.

Well a service locator may just be a wrapper around a particular inversion of control container such as Castle Windsor. The point is that the only place in which your code should (ideally) reference the container is at your composition root.

Because inversion of control containers support dependency chaining, when you resolve your root type from the container, all of its dependencies will be injected, and any descendent dependencies.

If you then wish to create further types at run time, then you can use factories, which could also have a reference to your container if you wish to take advantage of the dependency chaining offered by the container and the container mappings of interfaces against implementations.

When you use service locator, your code is calling locator for services everywhere. When you use inversion of control, there is only one place (composition root), where you call container. The rest of your app should not be container aware.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!