gpt4 book ai didi

c# - 如何在 EndRequest 中使用 Autofac?

转载 作者:可可西里 更新时间:2023-11-01 08:30:00 25 4
gpt4 key购买 nike

我在 .Net MVC 3 中使用 Autofac。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 期间用一个单独的范围来完成它,正如吉姆在下面建议的那样。但是,这意味着任何注册为 InstancePerHttpRequest 的服务都将在 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();
}

关于c# - 如何在 EndRequest 中使用 Autofac?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com