I'm doing a tutorial by book in MVC 4 using Ninject and I understand the concept of binding interfaces to concrete classes with injections, however I noticed that controller constructors usually pass the repositories associated with the bindings. My questions are when and how are the controller constructors fired after I specify a parameter in the constructor, how is that parameter passed? And what if I had overloaded constructors? Maybe I'm not understanding the Controller factory code, but to me it doesn't seem like it happens there, here are my example classes:
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.Domain.Abstract;
using SportsStore.WebUI.Models;
namespace SportsStore.WebUI.Controllers
{
public class ProductController : Controller
{
private IProductsRepository repository;
public int PageSize = 4;
public ProductController(IProductsRepository productRepo)
{
this.repository = productRepo;
}
public ViewResult List(string category, int page = 1)
{
ProductsListViewModel model = new ProductsListViewModel
{
Products = repository.Products
.Where(p=>category == null || p.Category == category)
.OrderBy(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = category==null?
repository.Products.Count():
repository.Products.Where(p=>p.Category==category).Count()
},
CurrentCategory = category
};
return View(model);
}
}
}
Controller Ninject Factory:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Moq;
using Ninject;
using SportsStore.Domain.Entities;
using SportsStore.Domain.Abstract;
using SportsStore.Domain.Concrete;
namespace SportsStore.WebUI.Infrastructure
{
public class NinjectControllerFactory: DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
Mock<IProductsRepository> mock = new Mock<IProductsRepository>();
mock.Setup(m => m.Products).Returns(new List<Product>{
new Product { Name = "Football", Price=25},
new Product {Name = "Surf board", Price=179},
new Product { Name = "running shoes", Price=95}
}.AsQueryable());
ninjectKernel.Bind<IProductsRepository>().To<EFProductRepository>();
}
}
}