项目结构图:

      

App_start文件夹中的文件是VS自己创建的,其中NinjectWebCommon类在创建之初并不存在。后面会再次提到!

添加一个Home控制器。代码如下:

using EssentialTools.Models;
using Ninject;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace EssentialTools.Controllers
{
public class HomeController : Controller
{
private IValueCalculator calc;
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}
};
public HomeController(IValueCalculator calcParam)
{
calc = calcParam;
} public ActionResult Index()
{
//IKernel ninjectKernel = new StandardKernel();
//ninjectKernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
//LinqValueCalculator calc = new LinqValueCalculator();
//return View(calc.ValueProducts(products));
ShoppingCart cart = new ShoppingCart(calc) { Products = products };
decimal totalValue = cart.CalculateProductTotal();
return View(totalValue);
} }
}

HomeController.cs

为控制器中的Index方法添加视图。代码如下:

@model decimal
@{
ViewBag.Title = "Index";
Layout = null;
} <div> Total value is $@Model</div>

Index.cshtml

创建Infrastructure文件夹,在该文件夹下创建Ninject的依赖解析器。代码如下:

using EssentialTools.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ninject; namespace EssentialTools.Infrastructure
{
public class NinjectDependencyResolver : IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel knernelParam)
{
kernel = knernelParam;
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>();
}
}
}

NinjectDependencyResolver.cs

在Models文件夹中攒关键1个接口,3个类。代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EssentialTools.Models
{
public interface IValueCalculator
{
decimal ValueProducts(IEnumerable<Product> products);
}
}

IValueCalculator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EssentialTools.Models
{
public class LinqValueCalculator : IValueCalculator
{
public decimal ValueProducts(IEnumerable<Product> products)
{
return products.Sum(p => p.Price);
}
}
}

LinqValueCalculator.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EssentialTools.Models
{
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
}

Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EssentialTools.Models
{
public class ShoppingCart
{
IValueCalculator calc;
public ShoppingCart(IValueCalculator calcParam)
{
calc = calcParam;
}
public IEnumerable<Product> Products { get; set; }
public decimal CalculateProductTotal()
{
return calc.ValueProducts(Products);
}
}
}

ShoppingCart.cs

使用nuget安装Ninject

工具→库程序包管理器→程序包管理器控制台

安装ninject内核包:
install-package Ninject -version 3.0.1.10
安装ninject内核包的拓展包:
install-package Ninject.Web.Common -version 3.0.0.7
对MVC3的引用(在mvc5中仍能用到)
install-package ninject.mvc3 -version 3.0.0.6

版本号最好带上,不带版本号,可能会出错!

安装好了之后NinjectWebCommon.cs文件就会出现。这时候需要为该类中的RegisterServices方法添加代码(注册依赖解析器)

RegisterServices方法代码如下:

private static void RegisterServices(IKernel kernel)
{
System.Web.Mvc.DependencyResolver.SetResolver(
new EssentialTools.Infrastructure.NinjectDependencyResolver(kernel));
}

RegisterServices方法代码

对浏览器发出请求到控制器处理请求这段时间发生的事!

1、浏览器向MVC框架发送一个请求Home的URL,MVC框架推测出该请求意指Home控制器,于是会创建HomeController类实例。

2、MVC框架在创建HomeController类实例过程中会发现其构造器有一个对IValueCalculator接口的依赖项,于是会要求依赖项解析器对此依赖项进行解析, 将该接口指定为依赖项解析器中的GetService方法所使用的类型参数。

3、依赖项解析器会将传递过来的类型参数交给TryGet方法,要求Ninject创建一个新的HomeController接口实例。

4、Ninect会检测到HomeController构造器与其实现类LilnqValueCalculator具有绑定关系,于是为该接口创建一个LinqValueCalculator类实例,并将其回递给依赖项解析器。

5、依赖项解析器将Ninject所返回的LilnqValueCalculator类作为IValueCalculator接口实现类实例回递给MVC框架

6、MVC框架利用依赖项解析器返回的接口类实例创建HomeController控制器实例,并使用该控制器实例对请求进行服务。

为已经能够正常运行的程序添加功能:为购物车内的东西打折。

在Models文件夹内添加一个叫做Discount的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EssentialTools.Models
{
public interface IDiscountHelper
{
decimal ApplyDiscount(decimal totalParam);
}
public class DefaultDiscounter : IDiscountHelper
{
public decimal DiscountSize { get; set; }
public decimal ApplyDiscount(decimal totalParam)
{
return (totalParam - (DiscountSize / 100m * totalParam));
}
}
}

Discount.cs

这个类里面包涵了一个接口,没有让接口和类进行分离(当然,这不是重点)。

更改后的计算价格的类LinqValueCalculator

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace EssentialTools.Models
{
public class LinqValueCalculator : IValueCalculator
{
private IDiscountHelper discounter; public LinqValueCalculator(IDiscountHelper discountParam)
{
discounter = discountParam;
}
public decimal ValueProducts(IEnumerable<Product> products)
{
return discounter.ApplyDiscount(products.Sum(p => p.Price));
}
}
}

LinqValueCalculator.cs

最后更改依赖项解析器类中的AddBindings方法

private void AddBindings()
{
kernel.Bind<IValueCalculator>().To<LinqValueCalculator>();
kernel.Bind<IDiscountHelper>().To<DefaultDiscounter>().WithPropertyValue("DiscountSize", 50M);
}

在Discount类中,有一个DiscountSize的属性,上面方法中使用了WithPropertyValue方法为这个属性赋了初始值。

在MVC项目中使用Ninject的更多相关文章

  1. 转 mvc项目中,解决引用jquery文件后智能提示失效的办法

    mvc项目中,解决用Url.Content方法引用jquery文件后智能提示失效的办法   这个标题不知道要怎么写才好, 但是希望文章的内容对大家有帮助. 场景如下: 我们在用开发开发程序的时候,经常 ...

  2. 谈谈MVC项目中的缓存功能设计的相关问题

    本文收集一些关于项目中为什么需要使用缓存功能,以及怎么使用等,在实际开发中对缓存的设计的考虑 为什么需要讨论缓存呢? 缓存是一个中大型系统所必须考虑的问题.为了避免每次请求都去访问后台的资源(例如数据 ...

  3. 在 ASP.NET MVC 项目中使用 WebForm、 HTML

    原文地址:http://www.cnblogs.com/snowdream/archive/2009/04/17/winforms-in-mvc.html ASP.NET MVC和WebForm各有各 ...

  4. MVC项目中如何判断用户是在用什么设备进行访问

    使用UAParser在C#MVC项目中如何判断用户是在用什么设备进行访问(手机,平板还是普通的电脑) 现在我们开发的很多web应用都要支持手机等移动设备.为了让手机用户能有更加好的用户体验,我们经常为 ...

  5. 在已有的Asp.net MVC项目中引入Taurus.MVC

    Taurus.MVC是一个优秀的框架,如果要应用到已有的Asp.net MVC项目中,需要修改一下. 1.前提约定: 走Taurus.MVC必须指定后缀.如.api 2.原项目修改如下: web.co ...

  6. ASP.NET MVC项目中App_Code目录在程序应用

    学习ASP.NET MVC,如果你是开发ASP.NET MVC项目的,也许你去为项目添加前ASP.NET项目的APP_Code目录,在这里创建与添加的Class类,也许你无法在MVC项目所引用. 那这 ...

  7. 如何在mvc项目中使用apiController

    文章地址:How do you route from an MVC project to an MVC ApiController in another project? 文章地址:How to Us ...

  8. 在ASP.NET MVC项目中使用极验验证(geetest)

    时间 2016-03-02 18:22:37 smallerpig 原文  http://www.smallerpig.com/979.html 主题 ASP.NET MVC   geetest开发体 ...

  9. MVC项目中,如何访问Views目录下的静态文件!

    <!--注意,是system.webServer节点,而非system.web--><system.webServer> <handlers> <add na ...

随机推荐

  1. Chrome开发者工具详解(一)之使用断点来调试代码上

    1.断点调试是啥?难不难? 断点调试其实并不是多么复杂的一件事,简单的理解无外呼就是打开浏览器,打开sources找到js文件,在行号上点一下罢了.操作起来似乎很简单,其实很多人纠结的是,是在哪里打断 ...

  2. 三剑客-sed(简写)

    打印操作:n命令所有行打印,第二行打印两遍 sed '2p' passwd只打印第二行sed -n '2p' passwd打印1~3行 sed -n '1,3p' passwd 打印带有'root'的 ...

  3. 对xxl-job进行simpleTrigger并动态创建任务扩展

    业务场景 需求上要求能实现quartz的simpleTrigger任务,同时还需要动态的创建任务而非在控制面板上创建,查阅xxl-job官方文档发现simpelTrigger其暂时还躺在to do l ...

  4. jquery ready load

    jq 加载三种写法 $(document).ready(function() { // ...代码... }) //document ready 简写 $(function() { // ...代码. ...

  5. python 安装时,为何pip install不是内部或者外部命令错误解决办法

    新安装的python 环境,第一次pip  install 却报不是内部或者外部命令错误 首先检查一下环境变量,可能时你没有设置环境变量 再说一遍,安装python环境时,记得出了python.exe ...

  6. Mysql检查列是否存在并新增、修改、删除列

    在MYSQL中,新增.修改.删除列时不能进行IF EXISTS判断,IF语句只能出现在存储过程当中,故博主用存储过程的方法新增.修改.删除列,修改列名称. DROP PROCEDURE IF EXIS ...

  7. Delphi ComboBox组件

  8. python、第一篇:初识数据库

    一 数据库管理软件的由来 基于我们之前所学,数据要想永久保存,都是保存于文件中,毫无疑问,一个文件仅仅只能存在于某一台机器上. 如果我们暂且忽略直接基于文件来存取数据的效率问题,并且假设程序所有的组件 ...

  9. On Java 8

    On Java 8本书原作者为 [美] Bruce Eckel,即<Java 编程思想>的作者.本书是事实上的 <Java 编程思想>第五版.<Java 编程思想> ...

  10. Java语言基础(1)

    1 计算机语言发展的分类 1)机器语言:由0,1组成(二进制),可以在计算机底层直接识别并执行(唯一). 2)汇编语言:由助记符组成,比机器语言简单.当执行的时候,把汇编语言转换为机器语言(0101) ...