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?
Yes, you can. Just take a dependency on the
IComponentContext:Update from the comments: the
IComponentContextinjected intoMyComponentdepends on the scope from whichMyComponentwas resolved. It is thus important to consider with what lifetime scopeMyComponentis registered. E.g. usingInstancePerLifetimeScope, the context will always resolve to the same scope in which the service depending onMyComponentlives.