DbContext Disposed after first request when using Ninject's InRequestScope()

dbcontext dependency injection dispose
use dbcontext in controller
ninject dbcontext
dbcontext per request
entity framework dbcontext lifetime
entity framework dbcontext dependency injection
autofac dbcontext
entity framework dbcontext best practices

I am new to both EF and Ninject so forgive me if this does not make sense :)

I have an MVC3 application with the Ninject and Ninject.Web.Common references. I am trying to inject a DbContext into my repositories. What I am seeing is that on the first request, everything works wonderfully but the subsequent requests return:

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:


My Service class:

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


My Repository class:

public class ProductRepository : IProductRepository {
    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)

My controller:

public class ProductController {
    public IProductService productService {get; set;}


If I remove .InRequestScope(), then it works fine - but then that causes problems with Entity Framework since objects are modified in multiple separate instances of the data context.

Set your repositories to be InRequestScope as well. They should dispose after each request.

Also with MVC you should be using constructor injection to inject your repository into your controller instance as well.

DbContext has been disposed when using Ninject · Ask Question I'm using Ninject and when I use injected repository ( InRequestScope ) to DbContext Disposed after first request when using Ninject's InRequestScope(). DbContext Disposed after first request when using Ninject's InRequestScope() System.InvalidOperationException: The operation cannot be completed because the DbContext has been disposed.

Naturally, soon after posting something clicked in my mind, and I was able to solve this.

The problem lies in the fact that the behavior of ActionFilters were changed in MVC3 and I had a filter that had my ProductService injected.

I suppose that the filter disposed of the service and that eventually disposed of the DbContext.

In my case, the solution was easy. I created a second DbContext that is used specifically for my filter. Since the filter does nothing more than query a select few tables to verify authorization to specific resources, I did not need the Unit of Work context that DbContext provides across a single request. I created a new service that uses the new DbContext. In this case, it is sufficient to be configured with InTransientScope()

DbContext Disposed after first request when using Ninject's InRequestScope() - asp.net-mvc-3. I am using EF 6 and Repository Pattern with Ninject DI. I need to create a new DbContext for every repository in the request scope. Each repository must use different DbContext in order to get data from EF 6 async method.

I'd argue against putting DbContext in a RequestScope because according to the NInject documentation, RequestScope relies on HttpContext. That's not guaranteed to be disposed at the end of your request.

I once experimented with putting DbContext in various object scopes, but always seemed to get inconsistent results.

The Ninject kernel maintains a weak reference to scoping objects and will automatically Dispose of objects associated with a scoping object when the weak reference to it is no longer valid. Since InRequestScope() uses HttpContext.Current or OperationContext.Current as the scoping object, any associated objects created will not be destroyed until HttpContext.Current or OperationContext.Current is destroyed. Since IIS/ASP.NET manages the lifecycle of these objects, disposal of your objects is tied to whenever IIS/.NET decides to destroy them and that may not be predictable.

I am using EF 6 and Repository Pattern with Ninject DI. working because repositories are disposing dbContext after EF 6 async method call. I am so newbie about Ninject and using it in my first time in my project right now. In general if an object does not create a disposable object, then he also doesn't have to dispose it. In this case Ninject is the one that creates the dbcontext and it also disposes it. Also since you pass around the dbcontext object to the Utilities class (that's a form of a dependency injection too), then you should be fine.

A DbContext makes use of important resources like database connections that created when as a web request comes in and they are disposed of when that request is completed. You also need to add the following line to the CreateKernel method in NInjectWebCommon.cs NET MVC · EF Code First. Managing the lifetime of a DbContext instance in your application is extremely important. A DbContext makes use of important resources like database connections that need to be released. If you do not properly dispose of a DbContext instance, the underlying database connections might never be released back to the connection pool.

On several occasions over the last couple of years I've seen the The first is incorrect configuration of lifestyle/lifetime of dependencies. MVC web application that uses a framework such as SimpleInjector or Ninject. In most cases your dependencies (including your DbContext) will use Request Scope so​  For quite a long time, I didn't include Entity Framework (EF) DbContext items in this mental pool of "things that should be injected". This is mostly because there was a very simple way of creating and disposing a DbContext and I was perfectly satisfied with using it. Until I wasn't.

You can register it using the following XML in your web.config That means that the NInject kernel gets disposed when the context is appropriately marked resources when the Request is ended (it listens to the HttpContext. So if you have more than one DbContext with the same connection whichever context is disposed first will close the connection (similarly if you have mixed an existing ADO.NET connection with a DbContext, DbContext will always close the connection when it is disposed).