2012-09-08 57 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

回答

相关问题