在ASP.NET Web API和ASP.NET Web MVC中使用Ninject
一、准备工作

二、在ASP.NET MVC中使用Ninject
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 ; }
}
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 ;
}
}
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);
}
}
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>();
}
}
NinjectRegister .RegisterFovMvc(); //为ASP.NET MVC注册IOC容器
public class ProductController : Controller
{
private IProductRepository repository; public ProductController(IProductRepository repository)
{
this .repository = repository;
} public ActionResult Index()
{
return View(repository.Products);
}
}
@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 >
}

三、在ASP.NET Web Api中使用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);
}
}
}
public static void RegisterFovWebApi( HttpConfiguration config)
{
config.DependencyResolver = new NinjectDependencyResolverForWebApi (Kernel);
}
NinjectRegister .RegisterFovWebApi( GlobalConfiguration.Configuration); //为WebApi注册IOC容器
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);
}
}
@{
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 >

在ASP.NET Web API和ASP.NET Web MVC中使用Ninject的更多相关文章
- ASP.NET Web API路由系统:Web Host下的URL路由
ASP.NET Web API提供了一个独立于执行环境的抽象化的HTTP请求处理管道,而ASP.NET Web API自身的路由系统也不依赖于ASP.NET路由系统,所以它可以采用不同的寄宿方式运行于 ...
- 【翻译】使用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 ...
- 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 ...
- 【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 ...
- ASP.NET Web API和ASP.NET Web MVC中使用Ninject
ASP.NET Web API和ASP.NET Web MVC中使用Ninject 先附上源码下载地址 一.准备工作 1.新建一个名为MvcDemo的空解决方案 2.新建一个名为MvcDemo.Web ...
- Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定
使用Knockout, Web API 和 ASP.Net Web Forms 进行简单数据绑定 原文地址:http://www.dotnetjalps.com/2013/05/Simple-da ...
- 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 创 ...
- 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 ...
- Web API 2 入门——使用Web API与ASP.NET Web窗体(谷歌翻译)
在这篇文章中 概观 创建Web窗体项目 创建模型和控制器 添加路由信息 添加客户端AJAX 作者:Mike Wasson 虽然ASP.NET Web API与ASP.NET MVC打包在一起,但很容易 ...
随机推荐
- 浅谈 vue实例 和 vue组件
vue实例: import Vue from 'vue'; import app from './app'; import myRouter from './routers'; new Vue({ e ...
- Hadoop基础-Protocol Buffers串行化与反串行化
Hadoop基础-Protocol Buffers串行化与反串行化 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们之前学习过很多种序列化文件格式,比如python中的pickl ...
- Java锁及AbstractQueuedSynchronizer源码分析
一,Lock 二,关于锁的几个概念 三,ReentrantLock类图 四,几个重要的类 五,公平锁获取 5.1 lock 5.2 acquire 5.3 tryAcquire 5.3.1 hasQu ...
- 穷竭搜索: POJ 2718 Smallest Difference
题目:http://poj.org/problem?id=2718 题意: 就是输入N组数据,一组数据为,类似 [1 4 5 6 8 9]这样在0~9之间升序输入的数据,然后从这些数据中切一 ...
- 计算广告学-多点归因模型(Multi-Touch Attribution Model)
计算广告学中的一个重要的问题是, 如果用户产生了一次转化(conversion, 比如购买, 注册等), 且该用户在转化之前看过大量不同频道(比如搜索, 展示, 社交等等)的广告, 那么我们如何确定是 ...
- codeforces9D How many trees?
传送门:http://codeforces.com/problemset/problem/9/D [题解] 树形dp,f(i,j)表示i个节点,高度为j的方案数,枚举左子树大小和哪一个子树高度为j-1 ...
- 【CodeForces】906 D. Power Tower 扩展欧拉定理
[题目]D. Power Tower [题意]给定长度为n的正整数序列和模数m,q次询问区间[l,r]累乘幂%m的答案.n,q<=10^5,m,ai<=10^9. [算法]扩展欧拉定理 [ ...
- 数据库(二)之SQL Server
什么是SQL SERVER? Microsoft发布的SQL Server产品是一个典型的关系型数据库管理系统. 功能强大 操作简便 可靠的安全性 SQL Server 2008体系结构 S ...
- 【leetcode 简单】 第八十一题 4的幂
给定一个整数 (32 位有符号整数),请编写一个函数来判断它是否是 4 的幂次方. 示例 1: 输入: 16 输出: true 示例 2: 输入: 5 输出: false 进阶: 你能不使用循环或者递 ...
- react页面间传递参数
react-router页面跳转,带请求参数 this.context.router.push({pathname:'/car_datail',state:{item:"hello" ...