博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ioc系列之Ninject之简单实用
阅读量:6997 次
发布时间:2019-06-27

本文共 2725 字,大约阅读时间需要 9 分钟。

我们在日常的开发当中,面向接口编程方式,是我们常用的编程方式,

还有在项目中使用设计模式的时候,也离不开接口编程。比如策略模式。

但随着接口的越来越多,我们在依赖反转的时候,平常都是用接口去实例化服务类。

如下:

I接口 接口变量=New 服务类()

但是,如果我们的接口越来越多,怎么办!

这个时候,我们就得使用我的依赖注入容器,比如spring.net,autofac,Ninject,Unity等太多了。

这些工具不仅可以提高编程速度,还可以方便我们解耦。让我符合OCP,DIP等原则。废话到此为主。

还是贴代码:

首先,接口:

public interface IProduct    {        IEnumerable
GetAll(); } public interface IProductA
where T:class,new() { IEnumerable
GetAll(); IList
Products { set; } }

服务类:

public class ProductNameA:IProduct    {        private static IList
products = new List
() { new Product{Id="1",ProductName="Iphone4s",Price="3788"} }; public IEnumerable
GetAll() { return products; } } public class ProductNameB
: IProductA
where T : class,new() { private IList
products; public IEnumerable
GetAll() { return products; } public IList
Products { set {products=value; } } }

注入容器:

using IProductService;using Ninject;namespace Service{    public class ProductService    {        IKernel kernel;        public ProductService(IKernel kernel)        {            this.kernel = kernel;            kernel.Bind
().To
(); //不带泛型约束注入 kernel.Bind(typeof(IProductA<>)).To(typeof(ProductNameB<>));//带泛型约束注入 } }}

客户端调用:

using IProductService;using Ninject;using Service;namespace Client{    class Program    {        private static IList
products = new List
() { new Product{Id="1",ProductName="Ipad3",Price="3188"} }; static void Main(string[] args) { IKernel kernel = new StandardKernel(); //实例化Ninject 容器 ProductService productService = new ProductService(kernel); //装载到服务类去初始化容器 IProduct iproduct = kernel.Get
(); //从容器里根据接口获取服务类 非泛型约束使用 Array.ForEach
(iproduct.GetAll().ToArray(), s => Console.WriteLine(s.ProductName)); //输出结果 IProductA
iproductA = kernel.Get
>();//从容器里根据接口获取服务类 泛型约束使用 iproductA.Products = products; //装载数据进去 Array.ForEach
(iproductA.GetAll().ToArray(), s => Console.WriteLine(s.ProductName)); //输出结果 /* 到此Ninject 的简单实用就结束了,我列举了2个常用方式 一个是非泛型 就是接口注入容器 一个泛型约束注入容器 总之,他们都是利用接口去容器获取服务类,不要再去依赖反转了,这样就可以轻松的解耦,多好 */ Console.ReadLine(); } }}

好了,太简单了吧,就是用接口 去绑定服务类到容器里。用的时候再用接口从容器里取服务类。

说白了就是:Bind<接口>().To(服务类) =》 接口 接口变量=Get<接口>();

Kernal 就是一个容器关系列表的容器。

其实,Ninject 还是有很复杂的,我们下一篇,将要讲解下。

示例代码下载

转载地址:http://hpavl.baihongyu.com/

你可能感兴趣的文章