zoukankan      html  css  js  c++  java
  • (依赖注入框架:Ninject ) 一 手写依赖注入

    什么是依赖注入?

    这里有一个场景:战士拿着刀去战斗:

    刀:

    class Sword 
    {
        public void Hit(string target)
        {
            Console.WriteLine($"Chopped {target} clean in half.");
        }
    }
    

    战士:

    class Samurai
    {
        readonly Sword sword;
        public Samurai() 
        {
            this.sword = new Sword();
        }
    }
    

    战士用刀:

    public void Attack(string target)
        {
            this.sword.Hit(target);
        }
    }
    

    OK,我们用刀武装了战士

    分析:刀和战士是高内聚的,因为战士依赖刀才得以创建,当你想给战士换一个武器的时候,你必须修改战士的实现方法,即构造函数

    修正一:使用接口来避免高内聚

    武器接口:

    interface IWeapon
    {
        void Hit(string target);
    }  

    继承接口的刀类:

    class Sword : IWeapon
    {
        public void Hit(string target) 
        {
            Console.WriteLine("Chopped {0} clean in half", target);
        }
    }  

    战士类:

    class Samurai
    {
        readonly IWeapon weapon;
        public Samurai() 
        {
            this.weapon = new Sword();
        }
    public void Attack(string target) 
        {
            this.weapon.Hit(target);
        }
    }
    

      

    分析:现在我们的战士可以武装不同的武器了 ,但是!!这个武器仍然是被创建在战士的构造函数里的,我们还是要改变战士的实现去给他更换武器.战士和武器仍然是高内聚的.

    修正二,将武器暴露出来

     修正后的战术类:

    class Samurai
    {
        readonly IWeapon weapon;
        public Samurai(IWeapon weapon) 
        {
            this.weapon = weapon;
        }
    public void Attack(string target) 
        {
            this.weapon.Hit(target);
        }
    }
    

      

     现在我们可以说:我们给战士注入了武器(构造函数注入),不需要修改战士的实现就能给他更换武器

     接口化并暴露依赖的实例  这被称作手写依赖注入

     

     But,当你的项目越来越大,对象越来越多,你将花费大量的时间去连接对象,那么,依赖注入库由此而来

    来自 <https://github.com/ninject/Ninject/wiki/Dependency-Injection-By-Hand> 

  • 相关阅读:
    常用知识点集合
    LeetCode 66 Plus One
    LeetCode 88 Merge Sorted Array
    LeetCode 27 Remove Element
    LeetCode 26 Remove Duplicates from Sorted Array
    LeetCode 448 Find All Numbers Disappeared in an Array
    LeetCode 219 Contains Duplicate II
    LeetCode 118 Pascal's Triangle
    LeetCode 119 Pascal's Triangle II
    LeetCode 1 Two Sum
  • 原文地址:https://www.cnblogs.com/swobble/p/10643955.html
Copyright © 2011-2022 走看看