我是新來的兩個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(),然後它工作正常 - 但隨後,導致實體框架的問題,因爲對象是在多個單獨修改數據上下文的實例。
構造函數注入vs屬性注入有什麼好處嗎? –
當然,它堅持構圖根。由於以下幾個原因,使用此模式的屬性並不合適。使用構造函數注入在這裏工作得很好,它可以讓依賴性儘早知道,因爲沒有理由將此作爲可選的依賴項,並且默認情況下是首選方法。見http://www.manning.com/seemann/這是關於這個主題的最好的書。 –
我正在使用DependencyResolver.Current.GetService <...而不是構造函數注入。這是否可能導致相同的問題? (由於DbContext已被處置,操作無法完成) –