輕量級IOC框架:Ninject

猴小新發表於2012-04-27
依賴注入 Ioc看似很高深的東西,但是用Ninject實現起來特別簡單

第一步  去http://www.ninject.org/download.html下載你所需要的版本

或者在建立專案後,直接在檢視--其他視窗---Package Manager Console裡輸入Install-Package Ninject -Project  你專案的名稱

第二步 建立一個控制檯專案

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject.Modules;
using Ninject;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Warrior warrior = new Warrior(new Sword());
            Warrior warrior1 = new Warrior(new Knife());
            warrior.kill("狼");
            warrior1.kill("兔子");
            Console.WriteLine("*******下面採用Ninject方式*******");
            using (IKernel kernel = new StandardKernel(new MyModule1()))
            {
                Warrior w = kernel.Get<Warrior>();
                w.kill("熊");
            }

            using(IKernel kernel=new StandardKernel(new MyModule2()))
            {
                Warrior w = kernel.Get<Warrior>();
                w.kill("老虎");
            }
            Console.ReadKey();
        }
    }

    public interface Iweapon
    {
         void Attack(string target);
    }

    public class Sword : Iweapon
    {
        public void Attack(string target)
        {
            Console.WriteLine("武士用刀砍殺{0}", target);
        }
    }
    public class Knife : Iweapon
    {
        public void Attack(string target)
        {
            Console.WriteLine("武士用匕首割斷了{0}的脖子", target);
        }
    }
    public class Warrior
    {
        public Iweapon _iweapon
        { get; private set; }
        
        [Inject]
        public Warrior(Iweapon weapon)
        {
            _iweapon = weapon;
        }

        public void kill(string target)
        {
            _iweapon.Attack(target);
        }
    }

    public class MyModule1 : NinjectModule
    {
        public override void Load()
        {
            this.Bind<Iweapon>().To<Sword>();
        }
    }

    public class MyModule2 : NinjectModule
    {
        public override void Load()
        {
            this.Bind<Iweapon>().To<Knife>();
        }
    }
}


 

相關文章