2015-09-03 48 views
0

我是新增的依賴注入,目前使用Ninject作爲我的DI。我一直在玩ASP.Net MVC 5應用程序,並一直在閱讀「Pro ASP.NET MVC 5」。我遵循了關於如何設置和使用Ninject的書中的示例。下面是我的註冊服務代碼:Ninject - 加載Ninject組件時出錯ICache

private static void RegisterServices(IKernel kernel) 
    { 
     kernel.Bind<ICustomerRepository>().To<CustomerRepository>(); 
     kernel.Bind<ICustomerUserDataRepository>().To<CustomerUserDataRepository>(); 
    } 

至於我的控制器我有以下:

public class CustomerController : Controller 
{ 
    private ICustomerRepository customerRepository; 

    public CustomerController(ICustomerRepository customerRepo) 
    { 
     this.customerRepository = customerRepo; 
    } 

    // GET: Customer 
    public ActionResult Index(int Id = 0) 
    { 
     Customer customer = customerRepository.GetCustomer(Id).First(); 

     return View(customer); 
    } 
} 

這種預期在書中正常工作。不過,我一直在玩一些其他代碼,並希望進一步使用Ninject來解決一些依賴關係。例如,我正在爲我的Razor視圖之一定製助手。在幫助我的代碼,我有以下幾點:

 using (IKernel kernel = new StandardKernel()) 
     {     
      ICustomerUserDataRepository customerUserDataRepo = kernel.Get<ICustomerUserDataRepository>(); 

當我運行它,它抱怨說是ICustomerUserDataRepository沒有綁定定義。我假設這是因爲我正在使用沒有定義綁定的新內核。我讀過你需要通過模塊在內核中加載綁定。所以,我提出以下幾點:

public class MyBindings : NinjectModule 
{ 
    public override void Load() 
    { 
     Bind<ICustomerUserDataRepository>().To<CustomerUserDataRepository>(); 
    } 
} 

設置我的內核下面當我再加載模塊:

using (IKernel kernel = new StandardKernel(new MyBindings())) 
{     
     ICustomerUserDataRepository customerUserDataRepo = kernel.Get<ICustomerUserDataRepository>(); 

然而,這會導致「錯誤加載Ninject組件ICACHE」錯誤消息時我執行應用程序。我會感謝一些幫助,我做錯了什麼,我不理解。我讀過多個定義的內核可能會導致此錯誤。我是不是想在我的幫助器方法中使用新的內核,因爲已經在RegisterServices()中使用並綁定了它?如果是這樣,我想在我的幫助器方法中訪問現有的內核?還是我在正確的軌道上,需要一個新的內核加載我的模塊中的特定綁定?謝謝。

回答

0

我是不是想在我的幫助器方法中使用新的內核,因爲一個已經在RegisterServices()下被使用和綁定了?

正確。每個應用程序只需要一個內核或組合根。我建議不要嘗試訪問輔助方法中的依賴關係,而是要在Controller中創建一個視圖模型(它可以訪問依賴項),然後將視圖模型傳遞給你的輔助方法。

+0

謝謝你的迴應,並會試試這個! – mike