Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/entity-framework/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 如何使用Ninject MVC扩展管理DbContext生存期_Asp.net Mvc_Entity Framework_Ninject - Fatal编程技术网

Asp.net mvc 如何使用Ninject MVC扩展管理DbContext生存期

Asp.net mvc 如何使用Ninject MVC扩展管理DbContext生存期,asp.net-mvc,entity-framework,ninject,Asp.net Mvc,Entity Framework,Ninject,嗨,这是关于我之前的一个问题 根据前面问题的答案中给出的参考,我不确定在使用Ninject和MVC时如何正确地实现DbContext的使用。是否有人推荐了一个这样做的例子?谢谢 我确实在这里看到了这1个示例: 但我不确定这如何能适应我目前项目的结构 这是我的一个存储库和接口的示例,其他存储库几乎完全相同,目前所有存储库都创建了一个新的上下文,我可能会更改此设置以将上下文注入存储库,但我认为这还不够 public interface IRepository<T> where T :

嗨,这是关于我之前的一个问题

根据前面问题的答案中给出的参考,我不确定在使用Ninject和MVC时如何正确地实现DbContext的使用。是否有人推荐了一个这样做的例子?谢谢

我确实在这里看到了这1个示例: 但我不确定这如何能适应我目前项目的结构

这是我的一个存储库和接口的示例,其他存储库几乎完全相同,目前所有存储库都创建了一个新的上下文,我可能会更改此设置以将上下文注入存储库,但我认为这还不够

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);
                }
            }
        }


    }
}
公共接口i假设,其中T:Entity{
IQueryable所有{get;}
T Find(int-id);
无效插入更新(T实体);
无效删除(int-id);
作废保存();
}
公共类RecipeRepository:IRepository
{
私有EatRateShareDbContext=新的EatRateShareDbContext();
公共图书馆
{
获取{return context.Recipes;}
}
公共配方查找(int-id)
{
返回context.Recipes.Find(id);
}
公共无效插入更新(配方)
{
如果(recipe.Id==默认值(int))
{
//新实体
context.Recipes.Add(recipe);
}否则
{
//现有实体
context.Entry(recipe.State=EntityState.Modified;
}
}
公共无效删除(int-id)
{
var recipe=context.Recipes.Find(id);
context.Recipes.Remove(配方);
}
公共作废保存()
{
尝试
{
SaveChanges();
}
捕获(DbEntityValidationException数据库异常)
{
foreach(databaseException.EntityValidationErrors中的var validationErrors)
{
foreach(validationErrors.validationErrors中的var validationError)
{
Trace.TraceInformation(“属性:{0}错误:{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);

    }
}
公共类ERSDbContext:DbContext
{
公共数据库集配方{get;set;}
公共数据库集{get;set;}
公共数据库集评论{get;set;}
公共数据库集课程{get;set;}
公共数据库集菜系{get;set;}
公共数据库集成员{get;set;}
公共数据库集步骤{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
//必须使用EF Fluent API指定这些映射,否则最终会导致
//外键字段被放置在配方表和成员表中,这不会
//建立多对多关系
modelBuilder.Entity()
.HasMany(r=>r.Members)
.有许多(m=>m.食谱)
.Map(x=>{
x、 ToTable(“Cookbooks”);//为多对多关系使用映射表
x、 MapLeftKey(“RecipeId”);
x、 MapRightKey(“成员ID”);
});
modelBuilder.Entity()
.HasRequired(x=>x.Author)
.有很多
.WillCascadeOnDelete(假);
}
}
我使用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;
        }
...
}
公共类控制器:控制器
{
私有只读IRepository memberRepository;
私人只读易读课程易读;
私人只读易读烹饪知识库;
私人只读易读易读;
公共食谱管理员(IRepository memberRepository、IRepository courseRepository、IRepository cuisineRepository、IRepository RecipereRepository)
{
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>();
    }      
私有静态无效注册服务(IKernel内核)
{
kernel.Bind().To();
kernel.Bind().To();
kernel.Bind().To();
kernel.Bind().To();
kernel.Bind().To();
}      

我找到了这个相关的帖子

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


使用Ninject时,我仍然需要清理此问题,但我正在回答我的问题,以便现在可以结束此问题。

相关:这是一个非常好的答案,我可以看到您建议使用上下文工厂和方法注入,或者让容器完成此工作。我想这意味着我想让Ninject完成所有的contextFactory设置和应用程序_BeginRequest和EndRequest可以帮助完成吗?我的问题更多的是关于如何实现这一点。老实说,我不确定。