Resolving Services
After you have yourcomponents registered with appropriate services exposed, you can resolve services from the built container and childlifetime scopes. You do this using theResolve()
method:
varbuilder=newContainerBuilder();builder.RegisterType<MyComponent>().As<IService>();varcontainer=builder.Build();using(varscope=container.BeginLifetimeScope()){varservice=scope.Resolve<IService>();}
You will notice the example resolves the service from a lifetime scope rather than the container directly - you should, too.
While it is possible to resolve components right from the root container, doing this through your application in some cases may result in a memory leak. It is recommended you always resolve components from a lifetime scope where possible to make sure service instances are properly disposed and garbage collected. You can read more about this in thesection on controlling scope and lifetime.
When resolving a service, Autofac will automatically chain down the entire dependency hierarchy of the service and resolve any dependencies required to fully construct the service. If you havecircular dependencies that are improperly handled or if there are missing required dependencies, you will get aDependencyResolutionException
.
If you have a service that may or may not be registered, you can attempt conditional resolution of the service usingResolveOptional()
orTryResolve()
:
// If IService is registered, it will be resolved; if// it isn't registered, the return value will be null.varservice=scope.ResolveOptional<IService>();// If IProvider is registered, the provider variable// will hold the value; otherwise you can take some// other action.IProviderprovider=null;if(scope.TryResolve<IProvider>(outprovider)){// Do something with the resolved provider value.}
BothResolveOptional()
andTryResolve()
revolve around the conditional nature of a specific servicebeing registered. If the service is registered, resolution will be attempted. If resolution fails (e.g., due to lack of a dependency being registered),you will still get a DependencyResolutionException. If you need conditional resolution around a service where the condition is based on whether or not the service can successfully resolve, wrap theResolve()
call with a try/catch block.
Additional topics for resolving services:
You may also be interested in checking out the list ofadvanced topics to learn aboutnamed and keyed services,working with component metadata, and other service resolution related topics.