zoukankan      html  css  js  c++  java
  • IOC框架之Ninject 简介

    本篇继续介绍IOC和DI的故事

    今天将以一个具体的IOC框架来介绍,Ninject 框架:

    1、Ninject简介

      Ninject是基于.Net平台的依赖注入框架,它能够将应用程序分离成一个个高内聚、低耦合(loosely-coupled, highly-cohesive)的模块,然后以一种灵活的方式组织起来。Ninject可以使代码变得更容易编写、重用、测试和修改。

      Ninject官方网址为:http://www.ninject.org/ 。

    2、项目引用Ninject.DLL 及 Ninject.Extensions.Xml.DLL

      关于程序集的引用大家可自行下载DLL文件也可以通过NuGet管理器来下载,在此不作说明。

    3、项目实例

      和上篇博客一样,我们通过具体例子来分享Ninject框架

      本篇继续采用上篇博客(学习 IOC 设计模式前必读:依赖注入的三种实现)案例进行说明,如下:

      首先,如同上篇博客背景一样,项目最初要求采用的是SqlServer数据库搭建,后来老板要求改为MySql数据库,再后来,老板要求改为Access数据库,再后来,老板又要求改为Oracle数据库,总之,这个老板的事很多...(请参考上篇博客)

      现在要求你设计一个解决方案,方便项目的扩展,你应该怎么设计?

      Ninject闪亮登场:

      首先,我们创建一个接口类,如下:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.Interface
    {
        public interface IDataAccess
        {
            void Add();
        }
    }
    复制代码

    由于项目将来很可能变更数据库,因此,在项目构建之初我们应先将常用的数据库实现,如下:

    Access数据库实现如下:

    复制代码
    using ConsoleNinject.Interface;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.DAL
    {
        public class AccessDAL : IDataAccess
        {
            public void Add()
            {
                Console.WriteLine("在ACCESS数据库中添加一条订单");
            }
        }
    }
    复制代码

    MySql数据库实现如下

    复制代码
    using ConsoleNinject.Interface;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.DAL
    {
        public class MySqlDAL : IDataAccess
        {
            public void Add()
            {
                Console.WriteLine("在MYSQL数据库中添加一条订单");
            }
        }
    }
    复制代码

    Oracle数据库实现如下:

    复制代码
    using ConsoleNinject.Interface;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.DAL
    {
        public class OracleDAL : IDataAccess
        {
            public void Add()
            {
                Console.WriteLine("在Oracle数据库中添加一条订单");
            }
        }
    }
    复制代码

    SqlServer数据库实现如下:

    复制代码
    using ConsoleNinject.Interface;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.DAL
    {
        public class SqlServerDAL : IDataAccess
        {
            public void Add()
            {
                Console.WriteLine("在SQLSERVER数据库中添加一条订单");
            }
        }
    }
    复制代码

    截止到现在,数据库层面的设计基本完成,现在我们来模仿一个下订单的类,分别采用构造方法注入和属性注入的方式,如下:

    复制代码
    using ConsoleNinject.Interface;
    using Ninject;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.UI
    {
        /// <summary>
        /// 订单类-通过构造方法注入
        /// </summary>
        public class OrderCls
        {
            private IDataAccess _datadal;
    
            [Inject]
            public OrderCls(IDataAccess DataDAL)
            {
                _datadal = DataDAL;
            }
    
            public void Add()
            {
                _datadal.Add();
            }
        }
    
        /// <summary>
        /// 订单类-通过属性注入
        /// </summary>
        public class OrderCls_SX
        {
            private IDataAccess _datadal;
    
            /// <summary>
            /// 属性注入
            /// </summary>
            public IDataAccess DataDAL
            {
                get
                {
                    return _datadal;
                }
                set
                {
                    _datadal = value;
                }
            }
    
            public void Add()
            {
                _datadal.Add();
            }
        }
    }
    复制代码

    最后,便是利用NinJect框架来构建依赖关系并输出结果,如下:

    复制代码
    using ConsoleNinject.DAL;
    using ConsoleNinject.Interface;
    using Ninject.Modules;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.UI
    {
        public class DataModule : NinjectModule
        {
            public override void Load()
            {
                Bind<IDataAccess>().To<AccessDAL>();
                Bind<IDataAccess>().To<MySqlDAL>();
                Bind<IDataAccess>().To<OracleDAL>();
                Bind<IDataAccess>().To<SqlServerDAL>();
                //
                Bind<OrderCls>().ToSelf();
                Bind<OrderCls_SX>().ToSelf();
            }
    
        }
    }
    复制代码

    上述代码,注意继承的类及Bind()...To()方法,使用这个方法来确定类与接口之间的依赖关系

    输出代码如下:

    复制代码
    using ConsoleNinject.DAL;
    using Ninject;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.UI
    {
        class Program
        {
            static void Main(string[] args)
            {
                IKernel kernal = new StandardKernel(new DataModule());
                OrderCls mysql = new OrderCls(kernal.Get<MySqlDAL>()); // 构造函数注入
                mysql.Add();
                //
                OrderCls access = new OrderCls(kernal.Get<AccessDAL>()); // 构造函数注入
                access.Add();
                //
                OrderCls_SX oracle = new OrderCls_SX();
                OracleDAL oracledal = new OracleDAL();//属性依赖注入
                oracle.DataDAL = oracledal;
                oracledal.Add();
                //
                OrderCls_SX sqlserver = new OrderCls_SX();
                SqlServerDAL sqlserverdal = new SqlServerDAL();//属性依赖注入
                sqlserver.DataDAL = sqlserverdal;
                sqlserverdal.Add();
                //
                Console.ReadLine();
            }
        }
    }
    复制代码

    这样,整个项目就设计完了,四种数据库都实现了!老板应该可以闭嘴了,即使再要求换成另外一个类型的数据库,我们也不怕,只需增加相应的DAL层及依赖关系Module并修改输出即可!

    这样,就基本符合设计模式的开闭原则,OrderCls代码内的业务逻辑代码是无需修改的!

    但是,上述的方式仍然属于手动注入的方式,如何能做到动态配置呢?换句话说,如何能通过修改配置文件来完成动态配置呢?

    Ninject是支持通过XML配置文件来实现动态注入的,这时需要引入:Ninject.Extensions.Xml.DLL

    首先创建XML配置文件:

    复制代码
    <?xml version="1.0" encoding="utf-8" ?>
    <module name="ServiceModule">
      <bind name="IDataAccess" service="ConsoleNinject.Interface.IDataAccess,ConsoleNinject.Interface" to="ConsoleNinject.DAL.SqlServerDAL,ConsoleNinject.DAL"/>
    </module>
    复制代码

    其次,书写Ninject XML 读取类,如下:

    复制代码
    using Ninject;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Ninject.Extensions.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleNinject.UI
    {
        public class XMLModuleContext : IDisposable
        {
            public XMLModuleContext()
            {
                var settings = new NinjectSettings() { LoadExtensions = false };
                Kernel = new StandardKernel(settings, new XmlExtensionModule());
            }
    
            protected IKernel Kernel { get; private set; }
    
            public void Dispose()
            {
                this.Kernel.Dispose();
            }
        }
        public class NinjectXMServiceLModule : XMLModuleContext
        {
            private static readonly NinjectXMServiceLModule instance = new NinjectXMServiceLModule();
            protected readonly XmlModule module = null;
            public NinjectXMServiceLModule()
            {
                var path = "D:/VS2012测试项目/ConsoleNinject/ConsoleNinject/Config/Ninject.xml"; //路径写死了 绝对路径
                Kernel.Load(path);
                module = Kernel.GetModules().OfType<XmlModule>().Single();
            }
    
            public static IKernel GetKernel()
            {
                return instance.Kernel;
            }
        }
    }
    复制代码

    最后,输出端代码如下:

    复制代码
    using ConsoleNinject.DAL;
    using ConsoleNinject.Interface;
    using Ninject;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleNinject.UI
    {
        class Program
        {
            static void Main(string[] args)
            {
                #region 手动注入
                IKernel kernal = new StandardKernel(new DataModule());
                OrderCls mysql = new OrderCls(kernal.Get<MySqlDAL>()); // 构造函数注入
                mysql.Add();
                //
                OrderCls access = new OrderCls(kernal.Get<AccessDAL>()); // 构造函数注入
                access.Add();
                //
                OrderCls_SX oracle = new OrderCls_SX();
                OracleDAL oracledal = new OracleDAL();//属性依赖注入
                oracle.DataDAL = oracledal;
                oracledal.Add();
                //
                OrderCls_SX sqlserver = new OrderCls_SX();
                SqlServerDAL sqlserverdal = new SqlServerDAL();//属性依赖注入
                sqlserver.DataDAL = sqlserverdal;
                sqlserverdal.Add();
                //
                #endregion
    
                #region 通过配置文件动态注入,说白了就是依赖关系写在了配置文件中
                var kernel = NinjectXMServiceLModule.GetKernel();
                var database = kernel.Get<IDataAccess>();
                OrderCls ordcls = new OrderCls(database);
                Console.WriteLine("我是通过配置文件确定的依赖关系!");
                ordcls.Add();
                #endregion
                Console.ReadLine();
            }
        }
    }
    复制代码

    OK,上述便是整个Ninject的代码实现,下面转载下Ninject常用的方法:

    (1)Bind<T1>().To<T2>()

    其实就是接口IKernel的方法,把某个类绑定到某个接口,T1代表的就是接口或者抽象类,而T2代表的就是其实现类

    例如:

    IKernel ninjectKernel = new StandardKernel();
    ninjectKernel.Bind<ILogger>().To<FileLogger>();

    (2)Get<ISomeInterface>()

    其实就是得到某个接口的实例,例如下面的栗子就是得到ILogger的实例FileLogger:

    ILogger myLogger= ninjectKernel.Get<ILogger>();

    (3)Bind<T1>() .To<T2>(). WithPropertyValue("SomeProprity", value);

    其实就是在绑定接口的实例时,同时给实例NinjectTester的属性赋值,例如:

    ninjectKernel.Bind<ITester>().To<NinjectTester>().WithPropertyValue("_Message", "这是一个属性值注入");

    (4)ninjectKernel.Bind<T1>().To<T2>(). WithConstructorArgument("someParam", value);

    其实就是说我们可以为实例的构造方法所用的参数赋值,例如:

    复制代码
    复制代码
    public class DefalutDiscountHelper : IDiscountHelper
        {
            private decimal discountRate;
            public decimal DiscountSize { get; set; }
            public DefalutDiscountHelper(decimal discountParam)
            {
                discountRate = discountParam;
            }
    
            public decimal ApplyDiscount(decimal totalParam)
            {
                return (totalParam - (discountRate / 100M * totalParam));
            }
        }
    复制代码
    复制代码
    ninjectKernel.Bind<IDiscountHelper>().To<DefalutDiscountHelper>().WithConstructorArgument("discountParam", 50M);

    (5)Bind<T1>().ToConstant()

    这个方法的意思是绑定到某个已经存在的常量,例如:

    StudentRepository sr = new StudentRepository();
    ninjectKernel.Bind<IStudentRepository>().ToConstant(sr);

    (6)Bind<T1>().ToSelf()

    这个方法意思是绑定到自身,但是这个绑定的对象只能是具体类,不能是抽象类。为什么要自身绑定呢?其实也就是为了能够利用Ninject解析对象本身而已。例如:

    ninjectKernel.Bind<StudentRepository>().ToSelf();
    StudentRepository sr = ninjectKernel.Get<StudentRepository>();

    (7)Bind<T1>().To<T2>().WhenInjectedInto<instance>()

    这个方法是条件绑定,就是说只有当注入的对象是某个对象的实例时才会将绑定的接口进行实例化

    ninjectKernel.Bind<IValueCalculater>().To<IterativeValueCalculatgor>().WhenInjectedInto<LimitShoppingCart>();

    (8)Bind<T1>().To<T2>().InTransientScope()或者Bind<T1>().To<T2>().InSingletonScope()

     这个方法是为绑定的对象指明生命周期其实

    ninjectKernel.Bind<IStudentRepository>().To<StudentRepository>().InTransientScope();
    //每次调用创建新实例
    ninjectKernel.Bind<IStudentRepository>().To<StudentRepository>().InSingletonScope();
    //每次调用是同一个实例

    (9)Load()方法

     这里的Load()方法其实是抽象类Ninject.Modules.NinjectModule的一个抽象方法,通过重写Load()方法可以对相关接口和类进行集中绑定,例如:

    复制代码
    复制代码
    public class MyModule : Ninject.Modules.NinjectModule
    {
        public override void Load()
        {
            Bind<ILogger>().To<FileLogger>();
            Bind<ITester>().To<NinjectTester>();
        }
    }
    复制代码
    复制代码

    这是通过Load()方法绑定之后的完整代码:

    复制代码
    复制代码
    private static IKernel kernel = new StandardKernel(new MyModule());
    static void Main(string[] args)
    {
        ITester tester = kernel.Get<ITester>(); // 因为是链式解析,因此只解析ITester即可,其它依赖的东东都会顺带解析  
    tester.Test(); Console.Read(); }
    复制代码
    复制代码

    (10)Inject属性

    在Inject中,我们可以通过在构造函数、属性和字段上加 Inject特性指定注入的属性、方法和字段等,例如下面的栗子,MessageDB有两个构造函数:int和object类型的。现在我们已经为int型的指定了Inject特性,因此在注入的时候选择的就是int型的构造函数;如果没有在构造函数上指定Inject特性,则默认选择第一个构造函数:

    复制代码
    复制代码
    public class MessageDB : IMessage
        {
            public MessageDB() { }
            public MessageDB(object msg)
            {
                Console.WriteLine("使用了object 参数构造:{0}", msg);
            }
    
            [Inject]
            public MessageDB(int msg)
            {
                Console.WriteLine("使用了int 参数构造:{0}", msg);
            }
    
            public string GetMsgNumber()
            {
                return "从数据中读取消息号!";
            }
        }
    复制代码
    复制代码
  • 相关阅读:
    PAT (Advanced Level) 1010. Radix (25)
    PAT (Advanced Level) 1009. Product of Polynomials (25)
    PAT (Advanced Level) 1008. Elevator (20)
    PAT (Advanced Level) 1007. Maximum Subsequence Sum (25)
    PAT (Advanced Level) 1006. Sign In and Sign Out (25)
    PAT (Advanced Level) 1005. Spell It Right (20)
    PAT (Advanced Level) 1004. Counting Leaves (30)
    PAT (Advanced Level) 1001. A+B Format (20)
    PAT (Advanced Level) 1002. A+B for Polynomials (25)
    PAT (Advanced Level) 1003. Emergency (25)
  • 原文地址:https://www.cnblogs.com/tuyile006/p/12575680.html
Copyright © 2011-2022 走看看