我目前正在啓動ASP.NET MVC 4,在我正在閱讀的書中,作者介紹了Ninject進行依賴注入。他創建了一個自定義的依賴關係解析器(我不完全理解它是如何工作的,但我認爲它的用途是輕鬆管理依賴關係解析)。ASP.NET MVC如何知道調用哪個控制器構造函數?
這裏是控制器代碼:
public class HomeController : Controller
{
private Product[] products = {
new Product {Name = "Kayak", Category = "Watersports", Price = 275M},
new Product {Name = "Lifejacket", Category = "Watersports", Price = 48.95M},
new Product {Name = "Soccer ball", Category = "Soccer", Price = 19.50M},
new Product {Name = "Corner flag", Category = "Soccer", Price = 34.95M}
};
private IValueCalculator calc;
public HomeController(IValueCalculator calcParam)
{
calc = calcParam;
}
public ActionResult Index()
{
ShoppingCart cart = new ShoppingCart(calc) { Products = products };
decimal totalValue = cart.CalculateProductTotal();
return View(totalValue);
}
}
而且自定義依賴解析器:
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver()
{
kernel = new StandardKernel();
AddBindings();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
private void AddBindings()
{
kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
}
}
在的Application_Start(),解析器設置:
DependencyResolver.SetResolver(new NinjectDependencyResolver());
問題:
ASP.NET MVC是如何知道要調用哪個控制器構造函數的?我認爲它將調用默認的構造函數,但沒有一個,我嘗試添加一個,仍然調用了帶參數的構造函數。
ASP.NET MVC是如何將IValueCalculator傳遞給構造函數的?
通過定義的路由配置。 –
Pro ASP.NET MVC 5! – Josh