将接口绑定到类Ninject的问题

时间:2014-07-02 11:23:12

标签: c# asp.net-mvc ninject

我有一个界面:

public interface IRepository<T>
    where T : Entity
{
    T Add(T entity);
    T Delete(int id);
    T Get(int id);
    T Update(T entity);
    IQueryable<T> Items { get; }
}

和班级:

public class EfRepository<T> : IRepository<T> where T : Entity

但是,我在绑定它们时遇到问题,所以这里是绑定代码并且它会一直突出显示

private void AddBindings()
    {
        ninjectKernel.Bind<IRepository<T>>().To<EfRepository<T>>();
    }

1 个答案:

答案 0 :(得分:1)

这是因为在您创建绑定的类中,它不知道T。

您正在寻找的是绑定开放式泛型。 这可以通过以下方式实现:

Bind(typeof(IGeneric<>)).To(typeof(Generic<>));

尝试一下,我想它应该可行(但是,它没有经过测试)。

在您的情况下,这意味着您的代码将如下所示:

private void AddBindings()
{
    ninjectKernel.Bind(typeof(IRepository<>)).To(typeof(EfRepository<>));
}