I'm still pretty new to using Autofac and one thing I miss in the documentation and examples is how to make it easy to get to the configured container from different places in a web application.
I know I can use the Autofac controller factory to automatically resolve constructor injected dependencies for controllers, but how about the other stuff you might need to resolve that is not injected yet.
Is there an obvious pattern I am not aware of for this?
Thank you!
The Autofac "way" is to have an IContext
constructor parameter. Autofac will inject an object that can be used to resolve types.
The context is usually the container behind the scenes, IContainer
implements the IContext
interface, though IContext
is limited to only doing resolves.
I know that the container should not be "overused", but I have, as the OP, classes that requires resolving types that is not known ahead of time (and thus cannot be used as constructor params). I find it useful in these cases, to think of the container as yet another service that can be used to resolve other services, and inject that like any other service.
If you feel that using IContext binds you to Autofac and you need to abstract that with your own interface this is just a matter of registering an IContext
wrapper class with your container.
Update: in Autofac 2, the IContext
is called IComponentContext
.