先附上源码下载地址

一、准备工作

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容器

最新文章

  1. TODO List - 任务表
  2. Red Gate(SQLToolbelt)SQL Server的安装与注册(破解)
  3. jquery实现动画
  4. [android] SQLite 数据库的升级 和 降级
  5. SDUT 2623:The number of steps
  6. android模块化app开发-4为APP减负
  7. spring容器启动的加载过程(三)
  8. 在mac OS10.10下安装 cocoapods遇到的一些问题
  9. luogu P5287 [HNOI2019]JOJO
  10. react-native android textinput显示不全的问题
  11. Python matplotlib.pyplot
  12. [HTML/CSS]三角形
  13. 《JAVA程序设计》_第二周学习总结
  14. Shiro笔记(五)Shiro授权
  15. 【托业】【新托业TOEIC新题型真题】学习笔记3-题库二-&gt;P5-6
  16. 移动端--touch事件与点透问题
  17. 网工最实用最常用的网络命令之一——Ping 命令详解(一)
  18. Mysql设置允许外网访问(图文)
  19. PostgreSQL学习----模式schema
  20. Mysql报错型注入总结

热门文章

  1. bzoj千题计划131:bzoj3993: [SDOI2015]星际战争
  2. HDU 3032 multi-sg 打表找规律
  3. warshall-floyd算法:POJ No 2139 Six Degress of Cowvin Bacon(任意两点最短路径))
  4. Nginx模块Lua-Nginx-Module学习笔记(一)Nginx Lua API 接口详解
  5. 单进程单线程的Redis如何能够高并发
  6. 六、强大的 Stream API
  7. An Insight to References in C++
  8. @Resource,@Autowired,@Inject3种注入方式
  9. datatable表格框架服务器端分页查询设置
  10. Strusts2笔记7--国际化