Ninject in ASP.NET MVC 有两个存储库

Ninject in ASP.NET MVC with two repositories

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

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

配置您的 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;
    }
    //...
}