UnityContainer.Resolve or ServiceLocator.GetInstance?

后端 未结 3 1725
北恋
北恋 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.

    0 讨论(0)
  • 2021-02-02 00:24

    I'm assuming that the ServiceLocator type is from the CommonServiceLocator project, and that you're using the Unity adapter, in which case GetInstance invokes container.Resolve, so both lines are equivalent.

    You can view the source here - http://commonservicelocator.codeplex.com/wikipage?title=Unity%20Adapter&referringTitle=Home

    0 讨论(0)
  • 2021-02-02 00:42

    Preferably you should avoid both ways of (ab)using your container.

    The ServiceLocator is considered an anti-pattern in modern application architecture.

    0 讨论(0)
提交回复
热议问题