zoukankan      html  css  js  c++  java
  • ASP.NET Web API和ASP.NET Web MVC中使用Ninject

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

     

     

     

    分类: Ninject
    标签: Ninject

  • 相关阅读:
    fastJson
    关于mybatis “org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)” 错误的问题。
    JVM——自定义类加载器
    NumberFormat数字格式化
    Java BigDecimal详解
    NumberUtils、ArrayUtils和RandomUtils工具类用法
    itext 生成 PDF(二)
    C语言中的可变参数列表
    归并排序--c语言实现
    机器学习实战学习笔记 一 k-近邻算法
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/4314787.html
Copyright © 2011-2022 走看看