title: How to manage a DbContext lifetime using the Ninject MVC extension
body: <p>Hi this is in relation to a previous question of mine.</p>
  
  <p><a href="https://stackoverflow.com/questions/12289180/efcodefirst-the-relationship-between-the-two-objects-cannot-be-defined-because">EFCodeFirst : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects</a></p>
  
  <p>I am unsure of how I can implement the use of my DbContext correctly when using Ninject &amp; MVC based on the reference given in the answer to my previous question. Does anyone have a recommended example of how this should be done? thanks.</p>
  
  <p>I did see this 1 example here: <a href="https://stackoverflow.com/questions/11921883/how-to-handle-dbcontext-when-using-ninject">How to handle DBContext when using Ninject</a>
  but I wasn't sure how this could fit into the current structure of my project.</p>
  
  <p>Here is an example of one of my repositories and the interface, the other repositories are pretty much identical and at the moment all create a new context, I will likely change this to inject the context into the repository but I dont think this will be enough. </p>
  
  <pre><code>public interface IRepository&lt;T&gt; where T : Entity {
      IQueryable&lt;T&gt; All { get; }
      T Find(int id);
      void InsertOrUpdate(T entity);
      void Delete(int id);
      void Save();
  }
  
  public class RecipeRepository : IRepository&lt;Recipe&gt;
  {
  
      private EatRateShareDbContext context = new EatRateShareDbContext();
  
      public IQueryable&lt;Recipe&gt; All
      {
          get { return context.Recipes; }
      }
  
      public Recipe Find(int id)
      {
          return context.Recipes.Find(id);
      }
  
      public void InsertOrUpdate(Recipe recipe)
      {
          if (recipe.Id == default(int))
          {
              // New entity
              context.Recipes.Add(recipe);
          } else
          {
              // Existing entity
              context.Entry(recipe).State = EntityState.Modified;
          }
      }
  
      public void Delete(int id)
      {
          var recipe = context.Recipes.Find(id);
          context.Recipes.Remove(recipe);
      }
  
      public void Save()
      {
          try
          {
              context.SaveChanges();
          }
  
          catch (DbEntityValidationException databaseException)
          {
              foreach (var validationErrors in databaseException.EntityValidationErrors)
              {
                  foreach (var validationError in validationErrors.ValidationErrors)
                  {
                      Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                  }
              }
          }
  
  
      }
  }
  </code></pre>
  
  <p>This is my DbContext</p>
  
  <pre><code>public class ERSDbContext : DbContext
  {
      public DbSet&lt;Recipe&gt; Recipes { get; set; }
      public DbSet&lt;Ingredient&gt; Ingredients { get; set; }
      public DbSet&lt;Review&gt; Reviews { get; set; }
      public DbSet&lt;Course&gt; Courses { get; set; }
      public DbSet&lt;Cuisine&gt; Cuisines { get; set; }
      public DbSet&lt;Member&gt; Members { get; set; }
      public DbSet&lt;Step&gt; Steps { get; set; }
  
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          // have to specify these mappings using the EF Fluent API otherwise I end up with
          // the foreign key fields being placed inside the Recipe and Member tables, which wouldn't
          // give a many-to-many relationship
          modelBuilder.Entity&lt;Recipe&gt;()
              .HasMany(r =&gt; r.Members)
              .WithMany(m =&gt; m.Recipes)
          .Map(x =&gt; {
              x.ToTable("Cookbooks"); // using a mapping table for a many-to-many relationship
              x.MapLeftKey("RecipeId");
              x.MapRightKey("MemberId");
          });
  
          modelBuilder.Entity&lt;Recipe&gt;()
              .HasRequired(x =&gt; x.Author)
              .WithMany()
              .WillCascadeOnDelete(false);
  
      }
  }
  </code></pre>
  
  <p>I use Ninject to inject my repositories into the controller as shown </p>
  
  <pre><code>    public class RecipesController : Controller
      {
          private readonly IRepository&lt;Member&gt; memberRepository;
          private readonly IRepository&lt;Course&gt; courseRepository;
          private readonly IRepository&lt;Cuisine&gt; cuisineRepository;
          private readonly IRepository&lt;Recipe&gt; recipeRepository;
  
          public RecipesController(IRepository&lt;Member&gt; memberRepository, IRepository&lt;Course&gt; courseRepository, IRepository&lt;Cuisine&gt; cuisineRepository, IRepository&lt;Recipe&gt; recipeRepository)
          {
              this.memberRepository = memberRepository;
              this.courseRepository = courseRepository;
              this.cuisineRepository = cuisineRepository;
              this.recipeRepository = recipeRepository;
          }
  ...
  }
  </code></pre>
  
  <p>For Ninject I am using the Nuget plugin which creates a NinjectWebCommon class and the below are my current bindings.</p>
  
  <pre><code>    private static void RegisterServices(IKernel kernel)
      {
          kernel.Bind&lt;IRepository&lt;Recipe&gt;&gt;().To&lt;RecipeRepository&gt;();
          kernel.Bind&lt;IRepository&lt;Member&gt;&gt;().To&lt;MemberRepository&gt;();
          kernel.Bind&lt;IRepository&lt;Cuisine&gt;&gt;().To&lt;CuisineRepository&gt;();
          kernel.Bind&lt;IRepository&lt;Course&gt;&gt;().To&lt;CourseRepository&gt;();
          kernel.Bind&lt;IRepository&lt;Review&gt;&gt;().To&lt;ReviewRepository&gt;();
      }      
  </code></pre>