Search code examples
asp.net-mvcrepositoryninject.web.mvc

Ninject in ASP.NET MVC with two repositories


I am working with ninject and I have problem with multiple repositories and interfaces. I managed to make ninject for one repo and one interface but problem appears when I am trying to ninject another repo with another interface with same database context. What is solution for multiple repositories and interfaces which are using same database context?

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

second repository

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

Solution

  • Configure your Ninject kernel to inject the same concrete instance of ApplicationDbContext in all your repositories and change your repositories constructors to receive the instance.

    NinjectWebCommon.cs:

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

    Your Repositories:

    public class RestaurantRepo : IRestaurantRepo
    {
        private readonly ApplicationDbContext _dbContext;
    
        public RestaurantRepo(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        //...
    }