I'm new to EF and Ninject, so forgive me if that doesn't make sense :)
I have an MVC3 application with Ninject and Ninject.Web.Common links. I am trying to inject DbContext into my repositories. I see that on the first request everything works wonderfully, but subsequent requests are returned:
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)
My bindings:
kernel.Bind<ISiteDataContext>().To<SiteDataContext>().InRequestScope();
kernel.Bind<IProductRepository>().To<ProductRepository>();
kernel.Bind<IProductService>().To<ProductService>();
My class of service:
public class ProductService : IProductService {
[Inject]
public IProductRepository repository {get; set;}
...
}
My repository class:
public class ProductRepository : IProductRepository {
[Inject]
public ISiteDataContext context {get; set;}
...
}
My SiteDataContext class:
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);
}
}
My controller:
public class ProductController {
[Inject]
public IProductService productService {get; set;}
...
}
If I delete .InRequestScope (), then it works fine, but then it causes problems with the Entity Framework, because the objects change in several separate instances of the data context.
source
share