12

我将 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)

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

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

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

编辑:我想在 EndRequest 期间使用单独的范围来完成它,正如 Jim 在下面建议的那样。但是,这意味着任何注册为的服务都InstancePerHttpRequest将在 EndRequest 期间获得一个新实例,这似乎并不理想。

4

1 回答 1

0

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

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

然后你可以在你的EndRequest

using (var scope = MvcApplication.ApplicationContainer.BeginLifetimeScope())
{
    var service = scope.Resolve<Stuff>();
    service.DoStuff();
}
于 2012-12-17T19:25:23.513 回答