我是Ninject的新手,所以我确信这是我做错了,我只是不知道是什么。我在我的MVC3 Web应用程序中使用Ninject和Ninject.MVC3。这是我想要做的一个例子。Ninject不注入和抛出空引用异常
我使用Repository模式:
public interface IRepository<T>
{
T Get(object id);
IList<T> GetAll();
void Add(T value);
void Update(T value);
void Delete(T value);
}
对于具体类型:
public Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Customer()
{
}
}
现在我有2个独立的仓库,一个缓存版本,需要注射到数据库存储库:
public CachedCustomerRepository : IRepository<Customer>
{
private IRepository<Customer> _repository;
public Customer Get(object id)
{
Customer cust = new Customer();
IList<Customer> custs = GetAll();
if (custs != null && custs.Count > 0)
cust = custs.FirstOrDefault(c => c.Id == int.Parse(id.ToString()));
return cust;
}
public IList<Customer> GetAll()
{
IList<Customer> custs = HttpRuntime.Cache["Customers"] as IList<Customer>;
if (custs == null)
{
custs = _repository.GetAll();
if (custs != null && custs.Count() > 0)
{
double timeout = 600000d;
HttpRuntime.Cache.Insert("Customers", custs, null, DateTime.UtcNow.AddMilliseconds(timeout), System.Web.Caching.Cache.NoSlidingExpiration);
}
else
{
throw new NullReferenceException();
}
}
return custs;
}
public void Add(Customer value)
{
throw new NotImplementedException();
}
public void Update(Customer value)
{
throw new NotImplementedException();
}
public void Delete(Customer value)
{
throw new NotImplementedException();
}
public CachedCustomerRepository()
{
}
[Inject]
public CachedCustomerRepository(IRepository<Customer> repository)
{
_repository = repository;
}
}
public class CustomerRepository : IRepository<Customer>
{
public Customer Get(object id)
{
Customer cust = new Customer();
IList<Customer> custs = GetAll();
if (custs != null && custs.Count > 0)
cust = custs.FirstOrDefault(c => c.Id == int.Parse(id.ToString()));
return cust;
}
public IList<Customer> GetAll()
{
//Customer retrieval code
}
public void Add(Customer value)
{
throw new NotImplementedException();
}
public void Update(Customer value)
{
throw new NotImplementedException();
}
public void Delete(Customer value)
{
throw new NotImplementedException();
}
public CachedCustomerRepository()
{
}
}
我建立了这样一个NinjectModule:
public class ServiceModule : NinjectModule
{
public override void Load()
{
Bind<IRepository<Customer>>().To<CustomerRepository>();
}
}
,我修改了AppStart的文件夹中的NinjectMVC3.cs获得创建内核时模块:
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(new ServiceModule());
RegisterServices(kernel);
return kernel;
}
在我的控制,我使用这样的:
public ViewResult Index()
{
IRepository<Customer> custRepo = new CachedCustomerRepository();
return View(custRepo.GetAll());
}
它吹在线_repository.GetAll()
在我的CachedCustomerRepository
。
我已经设置断点,以确保该CreateKernel()
正在执行和获取绑定,它是。我只是不确定为什么注射没有发生。另一方面,我不知道它是否重要,IRepository,Repositories和具体类型在一个单独的类库中,并在mvc3 web应用程序中引用。 Web应用程序和类库都提供了对Ninject的引用,并且该Web应用程序也提供了对Ninject.MVC3的引用。绑定和内核创建都在Web App中进行。
+1为每个人都经历了第一次学习依赖注入的挫折。 – TheCloudlessSky 2011-03-09 19:06:25