简体   繁体   English

在与Ninject绑定时使用通用类型 - 是否可能?

[英]Using Generic Types while binding with Ninject - is it possible?

Using Ninject, in my main program I call: 使用Ninject,在我的主程序中我打电话:

var kernel = new StandardKernel(new MyBindings());
var stuff = kernel.Get<MediaPresenter>();

Unfortunately I get an exception: 不幸的是我得到一个例外:

No matching bindings are available, and the type is not self-bindable. 没有匹配的绑定可用,并且该类型不可自绑定。

I really don't understand what that means. 我真的不明白这意味着什么。 Here is my binding class: 这是我的绑定类:

class MyBindings : NinjectModule
{
    public override void Load()
    {
        Bind<MediaPresenter>().ToSelf();
        Bind(typeof (Dao<Book>)).To(typeof (Dao<Book>));
    }
}

If I remove the line: 如果我删除该行:

Bind(typeof(Dao<Book>)).To(typeof(Dao<Book>));

The application runs, but then I get no bindings. 应用程序运行,但后来我没有绑定。

Why does that kind of thing not work and how can I fix it? 为什么这种事情不起作用,我该如何解决?

Can't test it right now but this should work: 现在无法测试,但这应该工作:

Bind(typeof (Dao<>)).To(typeof(Dao<>));

Using an interface, a probably better idea going forward: 使用界面,可能更好的想法:

Bind(typeof (IDao<>)).To(typeof(Dao<>));

为什么不在加载中执行此操作:

Bind<Dao<Book>>.ToSelf();

You should be codding against interface as it will make your code alot more testable. 您应该对接口进行编码,因为它会使您的代码更易于测试。 Have a look at this more info on Ninject binding 看看有关Ninject绑定的更多信息

Ninject Binding Ninject绑定

ok in your case you need to do this (not tested). 好吧,在你的情况下你需要这样做(没有测试)。 As long as you tell Inject the concrete implmentations it will take care of the injection at the right places for you depending that you have the right inject attributes in place in your code. 只要您告诉注入具体的实施,它将根据您在代码中具有正确的注入属性来处理在适当位置的注入。

  class MyBindings : NinjectModule
        {
            public override void Load()
            {
                Bind<IMediaPresenter>().To<MediaPresenter>;
                Bind<IDao>().To<Dao>();
                Bind<IBook>().To<Book>();
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM