I have registered a component like this in my Global.asax.cs:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExec
Registrations that are marked with InstancePerHttpRequest
are expected to be resolved from a particular nested lifetime scope that is created and disposed during each HTTP request.
If you add IWorkContext
as a constructor parameter to one of your controllers you will find that an instance is injected. In your code you are attempting to resolve your service from the root lifetime scope and not the nested "per request" lifetime scope.
If you want to test resolving the service without running up your application you will need to create a lifetime scope with the same tag as the one created during the HTTP request. In the MVC 3 integration the lifetime scope is tagged "httpRequest".
using (var httpRequestScope = container.BeginLifetimeScope("httpRequest"))
{
Assert.That(httpRequestScope.Resolve<IWorkContext>(), Is.Not.Null);
}
I think I will update the MVC integration to expose the "httpRequest" tag name publicly through the API so that string values don't need to be hard coded. It is also possible to pass your own ILifetimeScopeProvider
implementation to the AutofacDependencyResolver
so that you can control the creation of lifetime scopes outside of the ASP.NET runtime. This is useful in unit tests when there is no HTTP request available.
I'm doing this in WebForms:
this.RoutingService = ((Global)HttpContext.Current.ApplicationInstance).ContainerProvider.RequestLifetime.Resolve<RoutingService>();