0

We made the mistake to define a new DbContext in each of our repositories. So during development, we were walking into a lot of these kind of errors:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

So instead of disposing everywhere we figured the best thing to do is to make sure all of our repositories use the same context in each request. We had a NinjectControllerFactory initially, where we also placed our repository bindings. I installed the Ninject.Web.Commons nuget package and it created the NinjectWebCommon.cs file in App_Start.

I moved my bindings all over to the NinjectWebCommon file, and made the NinjectControllerFactory use the same kernel. I added our DbContext class as a binding and gave it the InRequestScope method.

ninjectKernel.Bind<EfDbContext>().ToSelf().InRequestScope();

Each repository is now using referring to the context through the constructor.

public class EfPageRepository : IPageRepository
{
    EfDbContext context;

    public EfPageRepository(EfDbContext dbContext)
    {
        this.context = dbContext;
    }
}

Now the project builds fine, but we are still getting the same error as I described in the beginning of this post. Did I forgot a step here? I really can't find why it is not working.

mipe34
  • 5,596
  • 3
  • 26
  • 38
Chris
  • 1,068
  • 2
  • 14
  • 30
  • 1
    Check this: http://stackoverflow.com/questions/10591203/ninject-3-inrequestscope-not-returning-the-same-instance-for-the-same-request?rq=1 – mipe34 Jun 21 '13 at 12:06
  • We had a custom factory, but it was setup to use the webcommons file's IKernel, so that was not the problem. However, installing Ninject.MVC3 seemed to have solved our problem. Thank you. – Chris Jun 26 '13 at 08:55

0 Answers0