2017-01-05 25 views
-1

这可能是一个愚蠢的问题,但我正在关注这个导师here试图使用Ninject模块

然后,我有,当我使用Ninject

名称“绑定”这下面的错误不存在。

发生了什么事?

using Ninject.Modules; 
using Ninject; 

namespace WCFExampleLibrary.Services 
{ 
    public class IocServices : NinjectModule 
    { 
     public override void Load() 
     { 
      Bind<ICourseRepository>().To<CourseRepository>(); 
      Bind<IStudentRepository>().To<StudentRepository>(); 
      Bind<IEnrollementRepository>().To<EnrollementRepository>(); 

     } 
    } 
} 


using System.Reflection; 
using Ninject; 
namespace WCFExampleLibrary.Services 
{ 
    public static class FactoryBuilder 
    { 
     private static IKernel _Kernal { get; set; } 
     public static T GetServices<T>() 
     { 
      _Kernal = new StandardKernel(); 
      _Kernal.Load(Assembly.GetExecutingAssembly()); 
      return _Kernal.Get<T>(); 
     } 
    } 
} 
+0

你是如何使用它?需要看到更多的代码。 –

回答

1

这里一个简单的例子(你必须从NinjectModule继承):

class Program 
    { 
     static void Main(string[] args) 
     { 

      Ninject.IKernel kernel = new StandardKernel(new TestModule()); 

      var samurai = kernel.Get<Samurai>(); 
      samurai.Attack("your enemy"); 

      Console.ReadLine(); 
     } 
    } 


    public interface IWeapon 
    { 
     string Hit(string target); 
    } 

    public class Sword : IWeapon 
    { 
     public string Hit(string target) 
     { 
      return "Slice " + target + " in half"; 
     } 
    } 

    public class Dagger : IWeapon 
    { 
     public string Hit(string target) 
     { 
      return "Stab " + target + " to death"; 
     } 
    } 

    public class Samurai 
    { 
     readonly IWeapon[] allWeapons; 

     public Samurai(IWeapon[] allWeapons) 
     { 
      this.allWeapons = allWeapons; 
     } 

     public void Attack(string target) 
     { 
      foreach (IWeapon weapon in this.allWeapons) 
       Console.WriteLine(weapon.Hit(target)); 
     } 
    } 

    class TestModule : Ninject.Modules.NinjectModule 
    { 
     public override void Load() 
     { 
      Bind<IWeapon>().To<Sword>(); 
      Bind<IWeapon>().To<Dagger>(); 
     } 
    } 

希望它能正常工作适合你。 问候,安迪