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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM