我正在使用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期间获得一个新实例,这似乎并不理想。
答案 0 :(得分: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();
}