项目结构图:

      

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. O003、准备 KVM 实验环境

    参考https://www.cnblogs.com/CloudMan6/p/5240770.html   KVM 是 OpenStack 使用的最广泛的Hypervisor,本节介绍如何搭建 KVM  ...

  2. with as 语句

    with就是一个sql片段,供后面的sql语句引用. 详情参见:https://www.cnblogs.com/Niko12230/p/5945133.html

  3. 07 Python中zip(),map(),filter(),reduce()用法

    一. zip() zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表. 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 ...

  4. scrapy-redis 实现分布式爬虫

    分布式爬虫 一 介绍 原来scrapy的Scheduler维护的是本机的任务队列(存放Request对象及其回调函数等信息)+本机的去重队列(存放访问过的url地址) 所以实现分布式爬取的关键就是,找 ...

  5. 如何使用python生成gif

    如何使用python生成gif? 在我的文件夹里面有很多图片,我们如何将其合成一个gif呢?可以使用PIL模块,这个模块在我的"python图像处理"板块中有详细介绍. # -*- ...

  6. 运维都该会的Socket知识!

    本篇博客转自赵班长 所有运维都会的Socket知识!!! 原创: 赵班长 新运维社区 什么是Socket? 大家都用电脑上网,当我们访问运维社区https://www.unixhot.com的时候,我 ...

  7. linux centos 7安装 apache php 及mariadb

    1安装Apache, PHP, MySQL以及php库组件. yum -y install httpd php mysql  php-mysql 2 安装apache扩展 yum -y install ...

  8. struts2 JSON 插件的使用

    1. 导入包: json-lib-2.3-jdk15.jar struts2-json-plugin-2.3.15.3.jar 2. 在struts.xml中修改配置如下: <package n ...

  9. 第二章 Vue快速入门-- 17 v-for指令的四种使用方式

    1.v-for循环普通数组 <!DOCTYPE html> <html lang="en"> <head> <meta charset=& ...

  10. spring cache 几个注解解释

    转自https://www.cnblogs.com/fashflying/p/6908028.html 从3.1开始,Spring引入了对Cache的支持.其使用方法和原理都类似于Spring对事务管 ...