【问题标题】:Ninject in ASP.NET MVC with two repositoriesNinject 在具有两个存储库的 ASP.NET MVC 中
【发布时间】:2016-12-12 19:51:32
【问题描述】:

我正在使用 ninject,但我遇到了多个存储库和接口的问题。我设法为一个 repo 和一个接口进行了 ninject,但是当我尝试使用具有相同数据库上下文的另一个接口 ninject 另一个 repo 时出现问题。 使用相同数据库上下文的多个存储库和接口的解决方案是什么?

NinjectWebCommon.cs

private static void RegisterServices(IKernel kernel)
    {
        //First one is working 
        kernel.Bind<IBookingRepo>().To<BookingsRepo>();
        //I suppose it can not be here
        kernel.Bind<IRestaurantRepo>().To<RestaurantRepo>();
    }

第二个仓库

    public class RestaurantRepo : IRestaurantRepo
        {
            //should i initialize second time db?
            ApplicationDbContext db = new ApplicationDbContext();
        ...
        }

【问题讨论】:

  • 您应该注入您的 ApplicationDbContext 而不是在您的存储库类中创建一个新实例。

标签: asp.net-mvc repository ninject.web.mvc


【解决方案1】:

配置您的 Ninject 内核以在您的所有存储库中注入相同的 ApplicationDbContext 具体实例,并更改您的存储库构造函数以接收该实例。

NinjectWebCommon.cs:

private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<ApplicationDbContext>().ToSelf().InRequestScope();
        kernel.Bind<IBookingRepo>().To<BookingsRepo>();
        kernel.Bind<IRestaurantRepo>().To<RestaurantRepo>();
    }

您的存储库:

public class RestaurantRepo : IRestaurantRepo
{
    private readonly ApplicationDbContext _dbContext;

    public RestaurantRepo(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }
    //...
}

【讨论】:

    猜你喜欢
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多