2012-06-22 34 views
5

我是新來的兩個EF和Ninject所以請原諒我,如果這沒有意義:)的DbContext設置的第一請求後,在使用Ninject的InRequestScope()

我與Ninject和Ninject.Web的MVC3應用。常見的參考。我正在嘗試在我的存儲庫中注入一個DbContext。我所看到的是,在第一次請求,一切奇妙的作品,但後續請求返回:

System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed. 
    at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() 
    at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression) 
    at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate) 

我的綁定:

kernel.Bind<ISiteDataContext>().To<SiteDataContext>().InRequestScope(); 
kernel.Bind<IProductRepository>().To<ProductRepository>(); 
kernel.Bind<IProductService>().To<ProductService>(); 

我的服務類:

public class ProductService : IProductService { 
    [Inject] 
    public IProductRepository repository {get; set;} 

    ... 
} 

我的倉庫等級:

public class ProductRepository : IProductRepository { 
    [Inject] 
    public ISiteDataContext context {get; set;} 

    ... 
} 

我SiteDataContext類:

public class SiteDataContext : DbContext, ISiteDataContext 
{ 
    static SiteDataContext() 
    { 
     Database.SetInitializer<SiteDataContext >(null); 
    } 

    public DbSet<Product> Products{ get; set; } 


    protected override void Dispose(bool disposing) 
    { 
     base.Dispose(disposing); 
    } 
} 

我的控制器:

public class ProductController { 
    [Inject] 
    public IProductService productService {get; set;} 

    ... 
} 

如果我刪除.InRequestScope(),然後它工作正常 - 但隨後,導致實體框架的問題,因爲對象是在多個單獨修改數據上下文的實例。

回答

5

很自然地,發佈了一些點擊在我腦海中的東西后,我就能解決這個問題。

問題在於ActionFilters的行爲在MVC3中發生了變化,而且我有一個過濾器,它已經注入了我的ProductService。

我想過濾器處理了服務並最終處理了DbContext。

就我而言,解決方案很簡單。我創建了第二個專門用於我的過濾器的DbContext。由於該過濾器只是查詢選定的幾個表來驗證對特定資源的授權,因此我不需要DbContext通過單個請求提供的工作單元上下文。我創建了一個使用新的DbContext的新服務。在這種情況下,使用InTransientScope()配置就足夠了

6

將您的存儲庫設置爲InRequestScope。他們應該在每次請求後處理。

此外,使用MVC,您應該使用構造函數注入來將您的存儲庫注入到控制器實例中。

+0

構造函數注入vs屬性注入有什麼好處嗎? –

+1

當然,它堅持構圖根。由於以下幾個原因,使用此模式的屬性並不合適。使用構造函數注入在這裏工作得很好,它可以讓依賴性儘早知道,因爲沒有理由將此作爲可選的依賴項,並且默認情況下是首選方法。見http://www.manning.com/seemann/這是關於這個主題的最好的書。 –

+1

我正在使用DependencyResolver.Current.GetService <...而不是構造函數注入。這是否可能導致相同的問題? (由於DbContext已被處置,操作無法完成) –

相關問題