2

我是 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();
}

谁能看到我做错了什么?

4

1 回答 1

2

它失败了,因为您的绑定不正确:

Bind<MainWindow>().To<FutureRealisticDateManager>();

FutureRealisticDataManager不继承自MainWindow. 相反,你应该写:

Bind<IRealisticDateManager>().To<FutureRealisticDateManager>();

FutureRealisicDateManager这告诉 Ninject 在请求时返回IRealisicDateManager

这样,当您调用k.Get<MainWindow>()内核时,将注入FutureRealisticDateManager到构造函数中。

于 2009-05-12T11:57:37.177 回答