我正在使用Ninject在MVC 4中进行教程,我理解了使用注入将接口绑定到具体类的概念,但是我注意到控制器构造函数通常会传递与绑定相关联的存储库。我的问题是在构造函数中指定参数后,控制器构造函数何时以及如何触发,该参数如何传递?如果我重载了构造函数怎么办?也许我不理解Controller工厂代码,但对我来说它似乎不会发生在那里,这是我的示例类:
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>();
}
}
}