在主项目之外使用公共服务定位器

发布于 2025-01-06 20:32:01 字数 452 浏览 0 评论 0原文

我最近从 StructureMap 跳到了 Ninject。一切都很顺利,直到我意识到 Ninject 没有 StructureMap 的 ObjectFactory(服务定位器)版本。

我发现 Common Service Locator 为包括 Ninject 在内的任何 IOC 容器提供了服务定位器模式。它在我的“启动”项目(例如网站)中运行良好。但是,如果我尝试从子项目(例如 Core 或 Data)访问 ServiceLocator.Current,则 CommonServiceLocator 似乎不知道我的任何依赖关系映射。

如何在子项目中使用 Common Service Locator?

注意:我知道关于 ServiceLocator 作为模式/反模式的争论。我发现 ServiceLocator 作为反模式和贫血域模型作为反模式之间存在权衡 - 有时它只是更容易和更容易。可使用服务定位器进行维护。

I recently made the jump from StructureMap to Ninject. All was smooth sailing until I realised that Ninject doesn't have a version of StructureMap's ObjectFactory (service locator).

I discovered Common Service Locator which provides the Service Locator Pattern with any IOC container including Ninject. It works great inside my 'start-up' project - e.g. WebSite. But if I try to access ServiceLocator.Current from subprojects, e.g. Core or Data it seems that CommonServiceLocator doesn't know about any of my Dependency mappings.

How do I use Common Service Locator from a sub-project?

N.B. I am aware of the debate about ServiceLocator as a pattern/anti-pattern. I've found that there is a trade-off between ServiceLocator as an anti-pattern and Anaemic Domain Model as an anti-pattern - sometimes its just much easier & maintainable to use a service locator.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一绘本一梦想 2025-01-13 20:32:01

使用工厂而不是直接访问容器。这使您的应用程序不受特定容器的影响,并防止使用服务定位器。

您必须访问内核的唯一情况是在您的组合根中,以及在一些非常罕见的情况下,您无法控制对象的创建。在这些情况下,您仍然可以将内核分配给单例对象或使用 ServiceLocator 使其可以从任何地方访问。

ServiceLocator 是一个静态对象。因此,与您访问它的位置没有区别。我假设您在 ServiceLocator 完全配置之前访问它。

Use factories instead of accessing the container directly. This keeps your application free from a specific container and prevents the usage of a service locator.

The only situations where you have to access the kernel is once in your composition root and in some very rare situations where you aren't in control of the object creation. In these situations you can still assign the kernel to a singleton object or use the ServiceLocator to make it accessable from anywhere.

ServiceLocator is a static object. Therefore there is no difference from where you are accessing it. I assume that you are accessing the ServiceLocator before it is fully confugured.

鹿港巷口少年归 2025-01-13 20:32:01

在不参与有关服务定位器使用的争论的情况下,您是否尝试过这个 NuGet 包 CommonServiceLocator.NinjectAdapter?

当我决定想要一个时,这就是我所使用的。

Without entering the debate on the use of a service locator, have you tried this NuGet Package CommonServiceLocator.NinjectAdapter?

When I decide I want one, this is what I've used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文