我是IoC / DI框架的新手。我正在尝试的第一个是Ninject框架。这似乎很简单,但我无法运行我的控制台应用程序。我一直得到一个ActivationException:
"Error activating MainWindow: the StandardProvider returned an instance of type FutureRealisticDateManager, which is not compatible with the requested service.
Using default binding from MainWindow to FutureRealisticDateManager (via StandardProvider)
declared by DateBindingModule.Load()
Activation path:
1) active request for MainWindow
from Program.Main()
using default binding from MainWindow to FutureRealisticDateManager (via StandardProvider)
declared by DateBindingModule.Load()"
我的代码非常简单。这是我的程序文件......
class Program
{
static void Main(string[] args)
{
IKernel k = new StandardKernel(new DateBindingModule());
MainWindow mw = k.Get<MainWindow>();
mw.Show();
Console.ReadLine();
}
}
这是我的ninject绑定模块......
public class DateBindingModule : StandardModule
{
public override void Load()
{
Bind<MainWindow>().To<FutureRealisticDateManager>();
}
}
这是接收注入类的类......
class MainWindow
{
private IRealisticDateManager _d;
[Inject]
public MainWindow(IRealisticDateManager dateManager)
{
_d = dateManager;
}
public void Show()
{
Console.WriteLine("*** MainWindow [" + _d.GetRealisticDate().ToString() + "] ");
}
}
这是注入的实际课程......
public class FutureRealisticDateManager : TestNinject.IRealisticDateManager
{
public DateTime GetRealisticDate()
{
return DateTime.Now.AddDays(15);
}
}
最后注入的类应该实现的简单接口......
public interface IRealisticDateManager
{
DateTime GetRealisticDate();
}
有人能看出我做错了吗?
答案 0 :(得分:2)
它失败了,因为你的绑定不正确:
Bind<MainWindow>().To<FutureRealisticDateManager>();
FutureRealisticDataManager
不会从MainWindow
继承。
相反,你应该写:
Bind<IRealisticDateManager>().To<FutureRealisticDateManager>();
这告诉Ninject在请求FutureRealisicDateManager
时返回IRealisicDateManager
。
这样当你调用k.Get<MainWindow>()
内核时会将FutureRealisticDateManager
注入构造函数。