先附上源码下载地址

一、准备工作

1、新建一个名为MvcDemo的空解决方案
2、新建一个名为MvcDemo.WebUI的空MVC应用程序
3、使用NuGet安装Ninject库
 

二、在ASP.NET MVC中使用Ninject

1、新建一个Product实体类,代码如下:
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 { set; get ; }
}
2、添加一个IProductRepository接口及实现
public interface IProductRepository
{
IQueryable <Product > Products { get; } IQueryable <Product > GetProducts(); Product GetProduct(); bool AddProduct(Product product); bool UpdateProduct(Product product); bool DeleteProduct(int productId);
} public class ProductRepository : IProductRepository
{
private List < Product> list;
public IQueryable < Product> Products
{
get { return GetProducts(); }
} public IQueryable < Product> GetProducts()
{
list = new List < Product>
{
new Product {ProductId = ,Name = "苹果",Category = "水果" ,Price = },
new Product {ProductId = ,Name = "鼠标",Category = "电脑配件" ,Price = },
new Product {ProductId = ,Name = "洗发水",Category = "日用品" ,Price = }
};
return list.AsQueryable();
} public Product GetProductById( int productId)
{
return Products.FirstOrDefault(p => p.ProductId == productId);
} public bool AddProduct( Product product)
{
if (product != null )
{
list.Add(product);
return true ;
}
return false ;
} public bool UpdateProduct( Product product)
{
if (product != null )
{
if (DeleteProduct(product.ProductId))
{
AddProduct(product);
return true ;
}
}
return false ;
} public bool DeleteProduct( int productId)
{
var product = GetProductById(productId);
if (product != null )
{
list.Remove(product);
return true ;
}
return false ;
}
}
3、添加一个实现了IDependencyResolver接口的Ninject依赖解析器类
public class NinjectDependencyResolverForMvc : IDependencyResolver
{
private IKernel kernel; public NinjectDependencyResolverForMvc( IKernel kernel)
{
if (kernel == null )
{
throw new ArgumentNullException( "kernel" );
}
this .kernel = kernel;
} public object GetService( Type serviceType)
{
return kernel.TryGet(serviceType);
} public IEnumerable < object> GetServices( Type serviceType)
{
return kernel.GetAll(serviceType);
}
}
4、添加一个NinjectRegister类,用来为MVC和WebApi注册Ninject容器
public class NinjectRegister
{
private static readonly IKernel Kernel;
static NinjectRegister()
{
Kernel= new StandardKernel ();
AddBindings();
} public static void RegisterFovMvc()
{
DependencyResolver .SetResolver(new NinjectDependencyResolverForMvc (Kernel));
} private static void AddBindings()
{
Kernel.Bind<IProductRepository >().To< ProductRepository>();
}
}
5、在Global.asax文件的Application_Start方法中添加下面代码:
NinjectRegister .RegisterFovMvc(); //为ASP.NET MVC注册IOC容器
6、新建一个名为ProductController的控制器,ProductController的构造函数接受了一个IProductRepository参数,当ProductController 被实例化的时候,Ninject就为其注入了ProductRepository的依赖.
public class ProductController : Controller
{
private IProductRepository repository; public ProductController(IProductRepository repository)
{
this .repository = repository;
} public ActionResult Index()
{
return View(repository.Products);
}
}
7、视图代码用来展示商品列表
@model IQueryable<MvcDemo.WebUI.Models. Product >

@{
ViewBag.Title = "MvcDemo Index" ;
} @ foreach ( var product in Model)
{
<div style=" border-bottom :1px dashed silver ;">
< h3> @product.Name </ h3>
< p> 价格:@ product.Price </ p >
</div >
}
8、运行效果如下:
 
 

三、在ASP.NET Web Api中使用Ninject

1、添加一个实现了IDependencyResolver接口的Ninject依赖解析器类
namespace MvcDemo.WebUI.AppCode
{
public class NinjectDependencyResolverForWebApi : NinjectDependencyScope ,IDependencyResolver
{
private IKernel kernel; public NinjectDependencyResolverForWebApi( IKernel kernel)
: base (kernel)
{
if (kernel == null )
{
throw new ArgumentNullException( "kernel" );
}
this .kernel = kernel;
} public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel);
}
} public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver; internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract .Assert(resolver != null ); this .resolver = resolver;
} public void Dispose()
{
resolver = null ;
} public object GetService( Type serviceType)
{
return resolver.TryGet(serviceType);
} public IEnumerable < object> GetServices( Type serviceType)
{
return resolver.GetAll(serviceType);
}
}
}
2、在NinjectRegister类中添加注册依赖解析器的方法
public static void RegisterFovWebApi( HttpConfiguration config)
{
config.DependencyResolver = new NinjectDependencyResolverForWebApi (Kernel);
}
3、在Global.asax文件的Application_Start方法中添加下面代码:
NinjectRegister .RegisterFovWebApi( GlobalConfiguration.Configuration); //为WebApi注册IOC容器
4、新建一个名为MyApiController的控制器
public class MyApiController : ApiController
{
private IProductRepository repository; public MyApiController(IProductRepository repository)
{
this .repository = repository;
}
// GET api/MyApi
[ HttpGet ]
public IEnumerable < Product> Get()
{
return repository.Products;
} // GET api/MyApi/5
[ HttpGet ]
public Product Get( int id)
{
return repository.Products.FirstOrDefault(p => p.ProductId == id);
}
}
5、视图代码用来展示商品列表
@{
ViewBag.Title = "ApiDemo Index" ;
} < script>
function GetAll() {
$.ajax({
url: "/api/MyApi" ,
type: "GET" ,
dataType: "json" ,
success: function (data) {
for (var i = ; i < data.length; i++) {
$( "#list" ).append("<h3>" + data[i].Name + "</h3>");
$( "#list" ).append("<p>价格:" +data[i].Price + "</p>");
}
}
});
} $( function () {
GetAll();
});
</ script> < h2> Api Ninject Demo </h2 >
< div id="list" style=" border-bottom :1px dashed silver ;"></ div >
6、运行效果如下:
 
至此,我们就实现了共用一个NinjectRegister类完成了为MVC和Web Api注册Ninject容器

在ASP.NET Web API和ASP.NET Web MVC中使用Ninject的更多相关文章

  1. ASP.NET Web API路由系统:Web Host下的URL路由

    ASP.NET Web API提供了一个独立于执行环境的抽象化的HTTP请求处理管道,而ASP.NET Web API自身的路由系统也不依赖于ASP.NET路由系统,所以它可以采用不同的寄宿方式运行于 ...

  2. 【翻译】使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定

    原文地址:http://www.dotnetjalps.com/2013/05/Simple-data-binding-with-Knockout-Web-API-and-ASP-Net-Web-Fo ...

  3. Asp.Net Web API VS Asp.Net MVC

    http://www.dotnet-tricks.com/Tutorial/webapi/Y95G050413-Difference-between-ASP.NET-MVC-and-ASP.NET-W ...

  4. 【ASP.NET Web API教程】3 Web API客户端

    原文:[ASP.NET Web API教程]3 Web API客户端 Chapter 3: Web API Clients 第3章 Web API客户端 本文引自:http://www.asp.net ...

  5. ASP.NET Web API和ASP.NET Web MVC中使用Ninject

    ASP.NET Web API和ASP.NET Web MVC中使用Ninject 先附上源码下载地址 一.准备工作 1.新建一个名为MvcDemo的空解决方案 2.新建一个名为MvcDemo.Web ...

  6. Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定

    使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定   原文地址:http://www.dotnetjalps.com/2013/05/Simple-da ...

  7. 002.Create a web API with ASP.NET Core MVC and Visual Studio for Windows -- 【在windows上用vs与asp.net core mvc 创建一个 web api 程序】

    Create a web API with ASP.NET Core MVC and Visual Studio for Windows 在windows上用vs与asp.net core mvc 创 ...

  8. Using MongoDB with Web API and ASP.NET Core

    MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which a ...

  9. Web API 2 入门——使用Web API与ASP.NET Web窗体(谷歌翻译)

    在这篇文章中 概观 创建Web窗体项目 创建模型和控制器 添加路由信息 添加客户端AJAX 作者:Mike Wasson 虽然ASP.NET Web API与ASP.NET MVC打包在一起,但很容易 ...

随机推荐

  1. P2787 语文1(chin1)- 理理思维

    P2787 语文1(chin1)- 理理思维 1.获取第x到第y个字符中字母k出现了多少次 2.将第x到第y个字符全部赋值为字母k 3.将第x到第y个字符按照A-Z的顺序排序 读字符串我再单个单个读我 ...

  2. 针对《面试心得与总结—BAT、网易、蘑菇街》一文中出现的技术问题的收集与整理

    最近,我在ImportNew网站上,看到了这篇文章,觉得总结的非常好,就默默的收藏起来了,觉得日后一定要好好整理学习一下,昨天突然发现在脉脉的行业头条中,居然也推送了这篇文章,更加坚定了我整理的信心. ...

  3. 用nginx搭建简单的文件下载服务器

    server {      listen       80;        #端口      server_name  localhost;   #服务名      charset utf-8; # ...

  4. PHP运算符的规律

    ^异或的规律:只有真真和假假位假 !非 判断失误的另一名比如true是false &只要有真都为真就是真其他都是假 $$就是左边是真的就不判断了 规律是一样的 |或只有假假都为假其他都是真

  5. 快速搭建Spring Boot项目

    Spring boot是Spring推出的一个轻量化web框架,主要解决了Spring对于小型项目饱受诟病的配置和开发速度问题. Spring Boot 包含的特性如下: 创建可以独立运行的 Spri ...

  6. Linux命令练习.ziw

    2017年1月10日, 星期二 Linux命令练习 1.统计/usr/bin/目录下的文件个数: # ls /usr/bin | wc -l 判断 /home/goldin目录是否有文件 2.取出当前 ...

  7. 转载http中302与301的区别

    http://blog.csdn.net/qmhball/article/details/7838989 一.官方说法301,302 都是HTTP状态的编码,都代表着某个URL发生了转移,不同之处在于 ...

  8. Linux Shell管道调用用户定义函数(使shell支持map函数式特性)

    Linux中有一个管道的概念,常用来流式的处理文本内容,比如一个文件对其中的每一行应用好几个操作,出于两个方面的考虑可能需要在管道中使用用户定义函数: 1. 刚需: 内置的sed/awk之类的可能没法 ...

  9. 《区块链100问》第81集:应用类项目Augur

    Augur是基于以太坊区块链打造的去中心化预测平台,于2015年6月正式发布,是以太坊上的第一款应用. Augur采用了一个叫“群体智慧”的概念,它的意思是,一群人的智慧会高于这群人中最聪明的人.所以 ...

  10. C++ Primer 5th 第14章 重载运算与类型转换

    当运算符作用域类类型的对象时,可以通过运算符重载来重新定义该运算符的含义.重载运算符的意义在于我们和用户能够更简洁的书写和更方便的使用代码. 基本概念 重载的运算符是具有特殊名字的函数:函数名由关键词 ...