2012-09-08 54 views
0

嗨,這是關於我以前的問題。如何使用Ninject MVC擴展來管理DbContext生命週期

EFCodeFirst : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

我不確定我怎麼能基於回答我剛纔的問題給出的參考使用Ninject & MVC時,正確地貫徹執行使用我的DbContext的。有沒有人有推薦的例子來說明如何做到這一點?謝謝。

我在這裏看到這個例子:How to handle DBContext when using Ninject 但我不確定這可能適合我目前的項目結構。

下面是我的一個倉庫和界面的例子,其他倉庫幾乎完全相同,目前都創建一個新的上下文,我可能會改變這個注入上下文到倉庫,但我不認爲這將是足夠的。

public interface IRepository<T> where T : Entity { 
    IQueryable<T> All { get; } 
    T Find(int id); 
    void InsertOrUpdate(T entity); 
    void Delete(int id); 
    void Save(); 
} 

public class RecipeRepository : IRepository<Recipe> 
{ 

    private EatRateShareDbContext context = new EatRateShareDbContext(); 

    public IQueryable<Recipe> 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); 
       } 
      } 
     } 


    } 
} 

這是我的DbContext

public class ERSDbContext : DbContext 
{ 
    public DbSet<Recipe> Recipes { get; set; } 
    public DbSet<Ingredient> Ingredients { get; set; } 
    public DbSet<Review> Reviews { get; set; } 
    public DbSet<Course> Courses { get; set; } 
    public DbSet<Cuisine> Cuisines { get; set; } 
    public DbSet<Member> Members { get; set; } 
    public DbSet<Step> 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<Recipe>() 
      .HasMany(r => r.Members) 
      .WithMany(m => m.Recipes) 
     .Map(x => { 
      x.ToTable("Cookbooks"); // using a mapping table for a many-to-many relationship 
      x.MapLeftKey("RecipeId"); 
      x.MapRightKey("MemberId"); 
     }); 

     modelBuilder.Entity<Recipe>() 
      .HasRequired(x => x.Author) 
      .WithMany() 
      .WillCascadeOnDelete(false); 

    } 
} 

我用Ninject如圖

public class RecipesController : Controller 
    { 
     private readonly IRepository<Member> memberRepository; 
     private readonly IRepository<Course> courseRepository; 
     private readonly IRepository<Cuisine> cuisineRepository; 
     private readonly IRepository<Recipe> recipeRepository; 

     public RecipesController(IRepository<Member> memberRepository, IRepository<Course> courseRepository, IRepository<Cuisine> cuisineRepository, IRepository<Recipe> recipeRepository) 
     { 
      this.memberRepository = memberRepository; 
      this.courseRepository = courseRepository; 
      this.cuisineRepository = cuisineRepository; 
      this.recipeRepository = recipeRepository; 
     } 
... 
} 

對於Ninject我使用的NuGet插件,它創建了一個NinjectWebCommon類注入我的倉庫到控制器下面是我目前的綁定。

private static void RegisterServices(IKernel kernel) 
    { 
     kernel.Bind<IRepository<Recipe>>().To<RecipeRepository>(); 
     kernel.Bind<IRepository<Member>>().To<MemberRepository>(); 
     kernel.Bind<IRepository<Cuisine>>().To<CuisineRepository>(); 
     kernel.Bind<IRepository<Course>>().To<CourseRepository>(); 
     kernel.Bind<IRepository<Review>>().To<ReviewRepository>(); 
    }  
+1

相關:http://stackoverflow.com/questions/10585478/one-dbcontext-per-web-request-why – Steven

+0

這是一個非常好的答案,我可以看到你建議使用上下文工廠和方法注射或讓容器做這項工作。我認爲這意味着我想讓Ninject完成所有的contextFactory設置,並且Application_BeginRequest和EndRequest可以幫助解決這個問題?我的問題更多的是關於如何實施這個說實話,我不確定。 – Pricey

回答

相關問題