我正在學習如何在我的asp.net MVC 4 web應用程序中使用Ninject。我不確定我是否有正確的概念。這就是我所做的。無法在asp.net mvc4 web應用程序中使ninject工作
1)使用管理的NuGet
2)安裝Ninject.MVC3添加在NinjectWebCommon.cs以下代碼(通過在的NuGet夾App_start自動添加本文件)
private static void RegisterServices(IKernel kernel)
{
**kernel.Bind<IProductRepository>.To<ProductRepository>;**
}
3)控制器代碼
Public Class ProductController
Inherits System.Web.Mvc.Controller
Private _rProduct As IProductRepository
'
' GET: /Product
Sub ProductController(ProductRepository As IProductRepository)
_rProduct = ProductRepository
End Sub
Function ProductList() As ActionResult
Return View(_rProduct.GetProducts())
End Function
End Class
4)IProductRepository代碼
Public Interface IProductRepository
Function GetProducts() As IQueryable(Of Product)
End Interface
5)ProductRepository代碼
Public Class ProductRepository
Implements IProductRepository
Public Function GetProducts() As IQueryable(Of Product) Implements IProductRepository.GetProducts
Return (New List(Of Product)() From {
New Product() With {.Name = "Football", .Price = 25},
New Product() With {.Name = "Surf board", .Price = 179},
New Product() With {.Name = "Running shoes", .Price = 95}
}.AsQueryable())
End Function
End Class
當我調試,控制不轉到 RegistryServices斷點()在NinjectWebCommon.cs,而不是來自於ProductController的的產品列表()。此時_rProduct是Nothing。你能解釋我發生了什麼嗎?
感謝
我做了你提到的改變,但得到了相同的結果。在調試時,它會觸發控制器 - > ProductList()中的中斷點,並且_rProducts仍然沒有任何結果! – user2721870
您是否記得恢復您的'RegisterServices'增加? – Jasen
我做了:) Private Sub RegisterServices(ByVal kernel As IKernel) kernel.Bind(Of IProductRepository).To(Of ProductRepository)() End Sub – user2721870