Using Autofac as a service locator
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 a开发者_开发知识库rgs, 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?
Yes, you can. Just take a dependency on the IComponentContext
:
public class MyComponent
{
IComponentContext _context;
public MyComponent(IComponentContext context)
{
_context = context;
}
public void DoStuff()
{
var service = _context.Resolve(...);
}
}
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.
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.
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.
精彩评论