容器注册的最佳实践?

发布于 2024-10-02 02:05:25 字数 288 浏览 2 评论 0原文

似乎有两个选项可用于在容器中注册类 - 显式(RegisterType().As)或自动装配(RegisterAssemblyTypes())。两者似乎都有相当明显的缺点。

显式注册意味着我得到了一个上帝类,它了解模块中的每种类型,并且很快就会变得庞大而笨重。

通过自动装配进行注册的风险是错误配置依赖项,例如接口的多个实现(最后一个注册获胜)或注册太多您永远无法解析的类型,或者必须显式覆盖注册,例如生命周期问题(某些类型是单例,有些不是)。

是否有最佳实践可以减少注册的痛苦/风险?

干杯 马特

There seems to be two options for registering your classes in a container - explicitly (RegisterType().As) or auto-wiring (RegisterAssemblyTypes()). Both seems to have pretty significant disadvantages.

Registering explicitly means I get a god class that knows about every type in my module, and gets large and unwieldy pretty quickly.

Registering via auto-wiring risks mis-configuring dependencies such as multiple implementations of an interface (last registration wins) or registering too many types that you'll never resolve, or having to explicitly override registrations for e.g. lifetime concerns (some types are singletons, some aren't).

Is there a best practice that makes registration less painful/risky?

Cheers
Matt

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

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

发布评论

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

评论(2

软的没边 2024-10-09 02:05:25

也许中间立场是向应该注册的类添加一个属性。该属性可以采用参数来指定其注册方式,例如组件的生命周期。

这对你自己来说并不难实现。如果这样做,您仍然有一个主要的注册函数,但它只需要知道要查找哪些属性(以及要查找哪些 DLL)而不是每个组件。

Maybe a middle ground is to add an attribute to classes that should be registered. That attribute can take parameters to specify how it is registered, for instance the lifetime of the component.

This isn't hard to implement yourself. If you do, you still have a main registration function, but it only needs to know what attributes to look for (and what DLLs to look in) rather than every component.

养猫人 2024-10-09 02:05:25

您是否考虑过使用 Autofac 的模块化支持?

在引导程序中或在构建容器的任何位置,您只需在应用程序中注册模块,然后在每个模块中注册您的类型。这使得它更容易阅读和理解。

Have you looked into using Autofac's moduling support?

In your bootstrapper or wherever you build your container, you simply register the modules in your application and then in each module you are registering your types. This makes it much easier to read and understand.

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