C# 如何在EndRequest中使用Autofac?
我正在将Autofac与.NETMVC3一起使用。似乎Autofac在Application_EndRequest中处理了生存期范围,这是有道理的。但当我试图在自己的代码中查找EndRequest期间执行的服务时,这会导致此错误:C# 如何在EndRequest中使用Autofac?,c#,asp.net,autofac,C#,Asp.net,Autofac,我正在将Autofac与.NETMVC3一起使用。似乎Autofac在Application_EndRequest中处理了生存期范围,这是有道理的。但当我试图在自己的代码中查找EndRequest期间执行的服务时,这会导致此错误: MESSAGE: Instances cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed.
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>();
}
public T GetInstance()
{
返回DependencyResolver.Current.GetService();
}
有没有办法让从EndRequest执行的代码利用Autofac进行服务解析
编辑:正如Jim在下面建议的那样,我想在EndRequest期间使用一个单独的作用域。然而,这意味着注册为
instanceperhtprequest
的任何服务都将在EndRequest期间获得一个新实例,这似乎并不理想 您可能需要创建自己的生存范围。假设您的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();
}
使用(var scope=mvcapapplication.ApplicationContainer.BeginLifetimeScope())
{
var service=scope.Resolve();
service.DoStuff();
}
请参见上面的“我的编辑”。这是可行的,但理想情况下,我希望EndRequest中的代码与我的其他代码具有相同的生存期范围,以便InstancePerHttpRequest
按预期工作。然后,您要么在EndRequest之前运行代码,要么直接挂接到Autofac,以便在Autofac结束之前启动代码。