使用Ninject将通用接口绑定到存储库时,获取"MissingMethodException:无法创建接口实例"

Las*_*eak 5 c# ninject asp.net-mvc-4 entity-framework-5

按照此处的指南,但不是StructureMap尝试使用Ninject.

每当我尝试将IRepository<SomeEntityType>一个参数注入到action方法中的参数时,它就会引发"MissingMethodException:无法创建接口的实例"错误.

更新:还没有找到bootstrapper.cs,我使用了MVC3 Ninject Nuget包.

 public ActionResult Index(IRepository<SomeEntityType> repo)
        {


            return View();
        }
Run Code Online (Sandbox Code Playgroud)

NinjectWebCommon.cs

        private static void RegisterServices(IKernel kernel)
    {
        string Cname = "VeraDB";
        IDbContext context = new VeraContext("VeraDB");
        kernel.Bind<IDbContext>().To<VeraContext>().InRequestScope().WithConstructorArgument("ConnectionStringName", Cname);
        kernel.Bind(typeof(IRepository<>)).To(typeof(EFRepository<>)).WithConstructorArgument("context",context);

    }      
Run Code Online (Sandbox Code Playgroud)

IRepository

    public interface IRepository<T> where T : class
{
    void DeleteOnSubmit(T entity);
    IQueryable<T> GetAll();
    T GetById(object id);
    void SaveOrUpdate(T entity);
}
Run Code Online (Sandbox Code Playgroud)

EFRepository

    public class EFRepository<T> : IRepository<T> where T : class, IEntity
{
    protected readonly IDbContext context;
    protected readonly IDbSet<T> entities;

    public EFRepository(IDbContext context)
    {
        this.context = context;
        entities = context.Set<T>();
    }

    public virtual T GetById(object id)
    {
        return entities.Find(id);
    }

    public virtual IQueryable<T> GetAll()
    {
        return entities;
    }

    public virtual void SaveOrUpdate(T entity)
    {
        if (entities.Find(entity.Id) == null)
        {
            entities.Add(entity);
        }

        context.SaveChanges();
    }

    public virtual void DeleteOnSubmit(T entity)
    {
        entities.Remove(entity);

        context.SaveChanges();
    }
}
Run Code Online (Sandbox Code Playgroud)

IEntity只是一个通用约束.

   public interface IEntity
{
    Guid Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ter 17

我犯了同样的错误.Ninject将参数注入构造函数,但是您向Index Controller操作添加了参数.

它应该如下所示:

public class HomeController : Controller
{
    private IRepository<SomeEntityType> _repo;

    public HomeController(IRepository<SomeEntityType> repo)
    {
        _repo= repo;
    }

    public ActionResult Index()
    {
        ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application. " +
                          _repo.HelloWorld();

        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

合理?

  • 我犯了同样的错误:) (2认同)

Ste*_*eve 1

这类错误通常表明您在运行时使用的 dll 版本与您在项目中引用的版本不同。

尝试手动将所有相关 dll 从项目目录复制到 bin 目录。

如果做不到这一点,请查看这篇(诚然,非常旧的)帖子,了解有关如何调试问题的一些想法。