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

先附上源码下载地址

一、准备工作

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 = 1,Name = "苹果",Category = "水果" ,Price = 1},
                new Product {ProductId = 2,Name = "鼠标",Category = "电脑配件" ,Price = 50},
                new Product {ProductId = 3,Name = "洗发水",Category = "日用品" ,Price = 20}
            };
            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 = 0; 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容器

时间: 2024-08-01 18:50:28

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

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

Chapter 3: Web API Clients 第3章 Web API客户端 本文引自:http://www.asp.net/web-api/overview/web-api-clients In this chapter, you'll learn: 本章你将学习: How to create client applications that call your web API. 如何创建调用Web API的客户端应用程序.包括以下几个部分: 3.1 Sample: Introducti

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 are schema independent. The schema can be mapped with Tables in a Relational Database. A schema in MongoDB is called as collection, and a record in thi

Asp.Net Web API VS Asp.Net MVC

http://www.dotnet-tricks.com/Tutorial/webapi/Y95G050413-Difference-between-ASP.NET-MVC-and-ASP.NET-Web-API.html Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP serv

Designing Evolvable Web API with ASP.NET 随便读,随便记 “The Internet,the World Wide Web,and HTTP”——HTTP

HTTP 我们将只聚焦在于与创建 Web APIs有关的部分. HTTP 是信息系统中的一个应用层协议,是Web的支柱. 其原先由 Berners-Lee, Roy Fielding 和 Henrik Frystyk Nielsen 三位计算机科学家们创作的.HTTP 为 客户端与服务器端之间跨网络相互传输信息定义了一个接口.它隐藏了双方的实现细 节. HTTP 设计用来戏剧性地改变系统,而容许一定程度上的延迟和数据的过时. 这种设计允许 计算机中间媒体,如代理服务器来协调通信,提供诸多好处,

Designing Evolvable Web API with ASP.NET 随便读,随便记 &ldquo;The Internet,the World Wide Web,and HTTP&rdquo;

1982年,诞生了 Internet; 1989年,诞生了World Wide Web . "World Wide Web"的构造为主要由 三部分构成: resources 资源 URIs 统一资源标识符 representations  呈现 其中,资源并不特指数据库之类的.任何东西可以是资源. URIs 分为两类: URLs 和URNs . URL 具有标识,并定位资源的功能. URN 则只是起标识作用. 通常讲,URI 默认指的是 URL. Google 建议,不要对实施了缓存的

Web Api Route 注册要放在 Mvc Route 注册前

今天想研究一下Web Api,写了一个测试Api,打开网站后浏览一下,可是却提示找不到方法,刚开始以为哪里配置错了,可找了半天也没见. 因为我是在一个现有Mvc站点做的Demo,所以打算新建一个Mvc网站,再试一下,新站点是正常的,对比一下Global文件,发现WebApiConfig和RouteConfig顺序不一样. 如果把新站点的RouteConfig也放在WebApiConfig之前,同样提示找不到方法.看来这两个配置有关联呀. ? 1 2 WebApiConfig.Register(G

Web API 基于ASP.NET Identity的Basic Authentication

今天给大家分享在Web API下,如何利用ASP.NET Identity实现基本认证(Basic Authentication),在博客园子搜索了一圈Web API的基本认证,基本都是做的Forms认证,很少有Claims认证(声明式认证),而我们在用ASP.NET Identity实现登录,认证,授权的时候采用的是Claims认证. 在Web API2.0中认证接口为IAuthenticationFilter,我们只需实现该接口就行.创建BasicAuthenticationAttribut

How ASP.NET Web API 2.0 Works?[持续更新中…]

一.概述 RESTful Web API [Web标准篇]RESTful Web API [设计篇] 在一个空ASP.NET Web项目上创建一个ASP.NET Web API 2.0应用 二.路由 ASP.NET的路由系统:URL与物理文件的分离 ASP.NET的路由系统:路由映射 ASP.NET的路由系统:根据路由规则生成URL ASP.NET Web API路由系统的几个核心类型 Web Host下的URL路由 三.消息处理管道 ASP.NET Web API标准的"管道式"设计

Web Api和Asp.Net mvc post请求区别

这是mvc的,mvc的post请求可以这样写参数,但是web api的不行.而且content_type:"application/json" 必须要写 下面这是web api的:content_type:"application/json" 必须要写