Abstracting IoC Container Behind a Singleton - Doing it wrong?

前端 未结 4 1564
日久生厌
日久生厌 2020-12-28 10:04

Generally, I like to keep an application completely ignorant of the IoC container. However I have ran into problems where I needed to access it. To abstract away the pain

4条回答
  •  旧时难觅i
    2020-12-28 10:20

    It all depends on the usage. Using the container like that is called the Service Locator Pattern. There are cases where it's not a good fit and cases where it do apply.

    If you google "service locator pattern" you'll see a lot of blog posts saying that it's an anti-pattern, which it's not. The pattern has simply been overused (/abused).

    For typical line of business applications you should not use SL as you hide the dependencies. You also got another problem: You can not manage state/lifetime if you use the root container (instead of one of it's lifetimes).

    Service locator is a good fit when it comes to infrastructure. For instance ASP.NET MVC uses Service Locator to be able to resolve all dependencies for each controller.

提交回复
热议问题