使用Autofac作为服务定位器 [英] Using Autofac as a service locator
问题描述
我使用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.
实际上,我的分量对Autofac的依赖。我宁愿更松散的耦合,但是这似乎并没有在这里是一种选择。有没有办法问(构造函数中指定参数时,或使用属性注入,或其他!)Autofac给我在我的构造函数的容器的引用?或者说,有没有有Autofac我提供一个神奇的服务定位器对象,可以解决任何问题一个更清洁的方式?
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?
推荐答案
是的,您可以。就拿在 IComponentContext
的依赖关系:
Yes, you can. Just take a dependency on the IComponentContext
:
public class MyComponent
{
public MyComponent(IComponentContext context)
{
_context = context;
}
public void DoStuff()
{
var service = _context.Resolve(...);
}
}
从注释更新:在 IComponentContext
注入为MyComponent
取决于从哪个为MyComponent
得到解决的范围。什么终身范围注册为MyComponent
来考虑这是重要的。例如。使用 InstancePerLifetimeScope
,上下文将始终解析到在其中根据不同的服务为MyComponent
同一范围内的生活。
Update from the comments: the IComponentContext
injected into MyComponent
depends on the scope from which MyComponent
was resolved. It is thus important to consider with what lifetime scope MyComponent
is registered. E.g. using InstancePerLifetimeScope
, the context will always resolve to the same scope in which the service depending on MyComponent
lives.
这篇关于使用Autofac作为服务定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!