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

时间:2013-04-08 14:28:49

标签: c# asp.net-mvc-4 ninject entity-framework-5

遵循指南here,而不是尝试使用Ninject的StructureMap。

当我尝试将IRepository<SomeEntityType>注入动作方法中的参数时,它会抛出“MissingMethodException:无法创建接口实例”错误。

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

 public ActionResult Index(IRepository<SomeEntityType> repo)
        {


            return View();
        }

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);

    }      

IRepository

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

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

IEntity只是一个通用约束。

   public interface IEntity
{
    Guid Id { get; set; }
}

2 个答案:

答案 0 :(得分:17)

我犯了同样的错误。 Ninject将参数注入到构造函数中,但是您向索引控制器操作添加了参数。

它应该是这样的:

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

有意义吗?

答案 1 :(得分:1)

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

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

如果做不到这一点,请查看this(不可否认,非常老)的帖子,了解如何调试问题的一些想法。