2012-12-17 16 views
12

我使用Autofac和.Net MVC 3.似乎Autofac在Application_EndRequest中處理了生命週期範圍,這很有意義。但是,這是造成這個錯誤,當我試圖找到我自己的代碼一種服務,EndRequest中執行:如何在EndRequest中使用Autofac?

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期間得到一個新實例,這似乎並不理想。

回答

0

您可能必須創建自己的生命週期範圍。假設你有你的global.asax.cs這樣的:在你EndRequest

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

然後,你可以做這樣的事情:

using (var scope = MvcApplication.ApplicationContainer.BeginLifetimeScope()) 
{ 
    var service = scope.Resolve<Stuff>(); 
    service.DoStuff(); 
} 
+0

見上面我的編輯。這是有效的,但理想情況下,我希望EndRequest中的代碼與我的其他代碼具有相同的生命週期範圍,以便「InstancePerHttpRequest」按預期工作。 – eliah

+0

然後你需要在EndRequest之前運行你的代碼,或者直接掛鉤Autofac,這樣你可以在Autofac結束之前觸發你的代碼。 –