I am doing a tutorial on the MVC 4 book using Ninject, and I understand the concept of binding interfaces to specific classes with injections, however I noticed that controller constructors usually pass repositories related to bindings. My questions are: when and how do controller constructors start after I specify a parameter in the constructor, how is this parameter passed? But what if I overloaded the designers? Perhaps I do not understand the factory controller code, but it seems to me that this is not so, here are my examples of 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);
}
}
}
Ninject Factory Controller:
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>();
}
}
}
source
share