这可能是一个愚蠢的问题,但我正在关注这个问题here。
当我使用Ninject
时,我有以下错误名称' Bind'不存在。
发生了什么事?
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>();
}
}
希望它适合你。 此致,安迪