如何在EndRequest中使用Autofac?

eli*_*iah 12 c# asp.net autofac

我正在使用Autofac和.Net MVC 3.似乎Autofac在Application_EndRequest中处理了生命周期范围,这是有道理的.但是当我尝试在我自己的代码中找到一个在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)
Run Code Online (Sandbox Code Playgroud)

作为参考,这是我用来尝试解析服务的代码:

    public T GetInstance<T>()
    {
        return DependencyResolver.Current.GetService<T>();
    }
Run Code Online (Sandbox Code Playgroud)

有没有什么办法可以让我从EndRequest执行的代码利用Autofac进行服务解析?

编辑:我想在EndRequest期间使用单独的范围进行操作,正如Jim在下面建议的那样.但是,这意味着注册的任何服务都InstancePerHttpRequest将在EndRequest期间获得新实例,这似乎是不理想的.

Jim*_*lla 0

您可能必须创建自己的生命周期范围。假设你的中有这样的东西global.asax.cs

public class MvcApplication : HttpApplication
{
    internal static readonly IContainer ApplicationContainer = InitAutofac();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的EndRequest

using (var scope = MvcApplication.ApplicationContainer.BeginLifetimeScope())
{
    var service = scope.Resolve<Stuff>();
    service.DoStuff();
}
Run Code Online (Sandbox Code Playgroud)