2012-06-15 68 views
0

我最近添加了Autofac 2.6.2到我的一個ASP.NET MVC項目中。Autofac拋出一個ObjectDisposedException

我現在面臨一個問題,當我想解決我WebDataContext我有一個的ObjectDisposedException:

Instances cannot be resolved and nested lifetimes cannot be 
created from this LifetimeScope as it has already been disposed. 

當我打電話給我的索引頁,我的瀏覽器發送大量請求,以獲得索引頁和所有其他所需資源(CSS,JS等)。其中一個請求可以解析IWebDataContext,而其他所有請求都會拋出ObjectDisposedException。

所以我的代碼看起來是這樣的:

protected void Application_Start() 
{ 
    MyContext.Initialize(); 
    DependencyResolver.SetResolver(new AutofacDependencyResolver(MyContext.Container)); 
    [...] 
} 

public class MyContext 
{ 
    public static IContainer Container { get; set; } 

    public static void Initialize() 
    { 
     ContainerBuilder container = new ContainerBuilder(); 
     IDependencyRegistrar registrar = new DependencyRegistrar(); 
     registrar.Register(container); 
     MyContext.Container = container.Build(); 
    } 

    public static IEngine Engine 
    { 
     get { return Singleton<IEngine>.Instance; } 
    } 
} 

public class DependencyRegistrar : IDependencyRegistrar 
{ 
    public void Register(object containerBuilder) 
    { 
     ContainerBuilder builder = (ContainerBuilder)containerBuilder; 
     builder.RegisterControllers(Assembly.GetExecutingAssembly()); 
     builder.RegisterType<WebDataContext>().As<IWebDataContext>().InstancePerHttpRequest(); 
      [...] 
} 

最後的方式,我解決我的註冊依賴:

public class MyEngine : IEngine 
{ 
    public T Resolve<T>() where T : class 
    { 
     return DependencyResolver.Current.GetService<T>(); 
    } 
} 

我想什麼:一個線程部署的WebDataContext和所有其他線程無法再訪問它。有人能告訴我,如果我忘記了一些東西,並且我的代碼是線程安全的嗎?

+0

你在這裏使用Autofac看起來不錯 - 你的任何單身人士都會打電話,並存儲'Resolve ()'的結果長於單個Web請求的持續時間嗎? –

回答

1

我發現了這個問題,我在我的Application_Error事件中調用了Resolve方法,因爲autofac之前已經部署了它的資源,這是不可能的!

相關問題