如何使用Ninject MVC扩展来管理DbContext生命周期

时间:2012-09-08 11:52:16

标签: asp.net-mvc entity-framework ninject

嗨,这与我之前的一个问题有关。

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

我不确定如何在使用Ninject&时正确实现我的DbContext的使用MVC基于我在上一个问题的答案中给出的参考。有没有人有一个如何做到这一点的推荐例子?感谢。

我在这里看到了这个例子: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 个答案:

答案 0 :(得分:0)

我发现了这篇相关帖子http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

通过使用工作单元和更通用的存储库,最好地回答了如何执行实现。

我仍需要清理它以便与Ninject合作,但我正在回答我的问题,所以我现在可以关闭它。