Resolve IContainer
You'll need IComponentContext
or ILifetimeScope
for most purposes. These are automatically provided by Autofac, so all you need to do is take a (constructor) dependency on one of them and the current instance will be injected.
Both interfaces provide the standard Resolve()
operations, while ILifetimeScope
extends IComponentContext
by adding methods for starting new nested lifetimes.
Components that want to use the services of the container to access other components need to do so within their own scope, rather than the 'global' IContainer
, so that the correct instance can be returned. E.g. within an HTTP request, the injected IComponentContext
or ILifetimeScope
will be the one for the current request.
Most problems that require an injected context can also be (often more elegantly) overcome using Relationship Types - see: http://autofac.readthedocs.org/en/latest/resolve/relationships.html.
stimms
I work as a freelance software developer with an interest in distributed systems, CQRS, cloud computing and ice cream. Ice cream most of all.
Updated on November 23, 2020Comments
-
stimms over 3 years
What is the suggested method of getting the Autofac container from inside a class in the application? Does Autofac provide for resolving an IContainer property on a class or do I need to store the container globally once I've build it?
-
Steven over 9 yearsIt would be good to note that there is a difference between auto-wiring that class and creating it using a delegate. In my case, the following worked:
builder.RegisterType<QueryProcessor>()
while the following failed with an ObjectDisposedException at runtime once theIComponentContext
was called:builder.Register(c => new QueryProcessor(c))
. -
Nicholas Blumhardt over 9 years
builder.Register(c => new QueryProcessor(c))
needs to be:builder.Register(c => new QueryProcessor(c.Resolve<IComponentContext>()))
-c
is a temporary that lives on a per-operation basis. HTH!