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.
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.