UnityContainer.Resolve or ServiceLocator.GetInstance?

后端 未结 3 1733
北恋
北恋 2021-02-01 23:57

It could seem a stupid question because in my code everything is working, but I\'ve registered a singleton this way with my Unity container _ambientContainer:

3条回答
  •  遇见更好的自我
    2021-02-02 00:17

    Passing around instances of the container to consumer classes isn't generally a good idea, since you are no longer guaranteed to have a single place in your application where components and services are being registered (known as the Composition Root).

    Classes should state their dependencies in their public API, ideally by specifying them as constructor arguments, which the container will automatically provide an instance for whenever it's been asked to resolve a specific type (a process known as Autowiring).

    Dependency Injection is usually the preferred choice but it isn't always applicable. In those cases using a Service Locator, like you're doing in your example, is the next best solution to decouple a class from its dependencies.

    In conclusion, if Dependency Injection is not an option, I would avoid having my classes reference the container directly and instead have them access it through a Service Locator.

提交回复
热议问题