12

I'm using Autofac with .Net MVC 3. It seems that Autofac disposes of the lifetime scope in Application_EndRequest, which makes sense. But that's causing this error when I try to find a service in my own code that executes during EndRequest:

 MESSAGE: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
STACKTRACE: System.ObjectDisposedException
  at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters)
  at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)
  at System.Web.Mvc.DependencyResolverExtensions.GetService[TService](IDependencyResolver resolver)

For reference, here's the code I'm using to try to resolve services:

    public T GetInstance<T>()
    {
        return DependencyResolver.Current.GetService<T>();
    }

Is there any way I can have code that is executed from EndRequest take advantage of Autofac for service resolution?

Edit: I thought of doing it with a separate scope just during EndRequest, as Jim suggests below. However, this means any services that are registered as InstancePerHttpRequest will get a new instance during EndRequest, which seems non-ideal.

eliah
  • 2,267
  • 1
  • 21
  • 23

1 Answers1

0

You'll probably have to create your own lifetime scope. Assuming you have something this in your global.asax.cs:

public class MvcApplication : HttpApplication
{
    internal static readonly IContainer ApplicationContainer = InitAutofac();
}

Then you could do something like this in your EndRequest:

using (var scope = MvcApplication.ApplicationContainer.BeginLifetimeScope())
{
    var service = scope.Resolve<Stuff>();
    service.DoStuff();
}
Jim Bolla
  • 8,265
  • 36
  • 54
  • See my edit above. This works, but ideally I would like my code in EndRequest to have the same lifetime scope as my other code, so that `InstancePerHttpRequest` works as expected. – eliah Dec 17 '12 at 21:53
  • Then you'll either have to run your code before EndRequest, or somehow hook into Autofac directly so that you can fire your code before Autofac wraps up. – Jim Bolla Dec 17 '12 at 22:00