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> 

  • 相关阅读:
    多种方式安装GitLabRunner
    rpm,docker,k8s三种方式安装部署GitLab服务
    利用curl命令访问Kubernetes API server
    在客户端电脑使用 kubectl 远程管理 Kubernetes
    利用 Nginx 反向代理搭建本地 yum 服务器
    Jenkins和Gitlab CI/CD自动更新k8s中pod使用的镜像说明
    1.在 Kubernetes 在快速安装 Harbor
    4.Gitlab CI 与 Kubernetes 的结合
    3.在 Kubernetes 上安装 Gitlab CI Runner
    2. 在 Kubernetes 上安装 Gitlab
  • 原文地址:https://www.cnblogs.com/swobble/p/10643955.html
Copyright © 2011-2022 走看看