使用 Autofac 作为服务定位器
我正在使用 Autofac 来处理应用程序中的依赖项注入。然而,我有一个组件在运行时执行一些反射魔法,但我不知道在编译时它需要什么依赖项。
通常,我会让这个组件直接引用容器并解析它想要的任何内容。但是,实例化此类的类没有对 Container 的引用。
实际上,我的组件依赖于 Autofac。我更喜欢松散的耦合,但这似乎不是一个选择。有没有办法询问(在构造函数参数中,或使用属性注入,或其他什么!)Autofac 为我的构造函数中的容器提供引用?或者,有没有一种更干净的方法让 Autofac 为我提供一个可以解决任何问题的神奇服务定位器对象?
I'm using Autofac to handle dependency injection in my application. However, I have one component that does some reflection magic at runtime and I don't know at compile-time what dependencies it will need.
Ordinarily, I would just have this component reference the Container directly and resolve whatever it wants. However, the class that is instantiating this class has no reference to the Container.
Effectively, my component has a dependency on Autofac. I'd prefer looser coupling, but that doesn't seem to be an option here. Is there a way to ask (in the constructor args, or using property injection, or whatever!) Autofac to give me a reference to the container in my constructor? Or, is there a cleaner way to have Autofac provide me with a magic service locator object that can resolve anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,你可以。只需依赖
IComponentContext
:从注释:注入到
MyComponent
中的IComponentContext
取决于解析MyComponent
的范围。因此,考虑MyComponent
注册的生命周期范围非常重要。例如,使用InstancePerLifetimeScope
,上下文将始终解析为依赖于MyComponent
的服务所在的相同范围。Yes, you can. Just take a dependency on the
IComponentContext
:Update from the comments: the
IComponentContext
injected intoMyComponent
depends on the scope from whichMyComponent
was resolved. It is thus important to consider with what lifetime scopeMyComponent
is registered. E.g. usingInstancePerLifetimeScope
, the context will always resolve to the same scope in which the service depending onMyComponent
lives.假设你有两个组件,A和B。
如果A在使用B之前需要了解X关于B的信息,这就是元数据询问,并且在优秀的帖子。
此外,即使您无法使您的设计适应该帖子,您也应该再次尝试确定是否确实需要使用 DI 容器作为服务定位器。
在撰写本文时,我能找到的描述它的最佳博客文章是 this< /a> 一。
Supposing you have two components, A and B.
If A needs to know X about B before using it, this is Metadata interrogation and it is described in this excellent post.
Furthermore, even if you can't adapt your design to that post, you should again try to make sure if you really need to use your DI Container as a Service Locator.
At the time of this writting, the best blog post I could find describing it is this one.
在其他情况下,当您的组件不是使用 DI 创建的时,您仍然可以使用服务定位器模式。 CodePlex 上的公共服务定位器库非常适合此目的。
In other cases, when your component is not created by using DI, you still can use the service locator pattern. The Common Service Locator library on CodePlex is perfect for the purpose.