Following the guide here, but instead of StructureMap attempting to use Ninject.
It throws up the "MissingMethodException: Cannot create an instance of an interface" error any time I attempt to inject an IRepository<SomeEntityType>
into a parameter in an action method.
Update: Also giving bootstrapper.cs not found, I used the MVC3 Ninject Nuget package.
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 just acts as a generic constraint.
public interface IEntity
{
Guid Id { get; set; }
}