Dependency Injection in .NET with examples?

前端 未结 8 1497
别跟我提以往
别跟我提以往 2020-11-27 14:31

Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on

8条回答
  •  失恋的感觉
    2020-11-27 15:07

    Ninject must have one of the coolest sample out there: (pieced from the sample)

    interface IWeapon {
      void Hit(string target);
    }
    class Sword : IWeapon {
      public void Hit(string target) {
        Console.WriteLine("Chopped {0} clean in half", target);
      }
    }
    class Shuriken : IWeapon {
      public void Hit(string target) {
        Console.WriteLine("Shuriken tossed on {0}", target);
      }
    }
    class Samurai {
      private IWeapon _weapon;
    
      [Inject]
      public Samurai(IWeapon weapon) {
        _weapon = weapon;
      }
    
      public void Attack(string target) {
        _weapon.Hit(target);
      }
    }
    
    class WeaponsModule: NinjectModule {
      private readonly bool _useMeleeWeapons;
    
      public WeaponsModule(bool useMeleeWeapons) {
        _useMeleeWeapons = useMeleeWeapons;
      }
    
      public void Load() {
        if (useMeleeWeapons)
          Bind().To();
        else
          Bind().To();
      }
    }
    
    class Program {
      public static void Main() {
        bool useMeleeWeapons = false;
        IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
        Samurai warrior = kernel.Get();
        warrior.Attack("the evildoers");
      }
    }
    

    This, to me, reads very fluently, before you start up your dojo you can decide how to arm your Samurais.

提交回复
热议问题