12

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.
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の間に別のスコープでそれを行うことを考えました。ただし、これは、InstancePerHttpRequestEndRequest中に新しいインスタンスを取得するように登録されているサービスを意味しますが、これは理想的ではないようです。

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 に答える