我是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