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-ti
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.
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.
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.