I am building a four-layer system with MVC3 as the main front end, but containing long-running tasks that are run asynchronously by the service layer and report progress, which MVV will show using Ajax. I am using Autofac for dependency injection (DI) mainly because the interface and documentation is good and because its fast (see this excellent study on DI speed by Philip Mateescu).
My question is about how to set up Autofac to handle the two scopes of the injected items, i.e. the MVC3 dependencies have to be PerHttpRequest but the async task dependencies need to be InstancePerLifetimeScope.
Clearly the service layer will need to use a separate DI to resolve the long-running task’s dependencies. What is the best way of doing that?
Update – June 2014
I have updated this answer as the best practice on using AutoFac has moved on, plus changes in MVC. The change is that best practice in AutoFac is now to define any instances that need to last for the whole lifetime of the access, in the case of MVC the HttpRequest, by using the .InstancePerLifetimeScope() suffix. See below for an example:
Having done that you no longer need to specify the name of the new lifetime scope you are creating inside the task (see original answer, which has been updated, below).
Here are a few other notes about tasking in MVC that you might find useful:
Original post, but updated (note: you must register lifetime scope instances as shown above)
I have found how to handle an async task with dependencies though the Google Autofac group. It turns out that you can access the MVC level container and then create a new lifetime scope of the resolve. There are a number of ways of doing it but this answer by Alex Meyer-Gleaves (who is an expert) provides the answer. Alex suggests the following code below for running a task that has a different scope.
There is a link to a more detailed blog post here on the subject in Alex’s post which is also very useful.