按照此处的指南,而不是 StructureMap 尝试使用 Ninject。
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);
}
存储库
public interface IRepository<T> where T : class
{
void DeleteOnSubmit(T entity);
IQueryable<T> GetAll();
T GetById(object id);
void SaveOrUpdate(T entity);
}
EF存储库
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; }
}