2
我想了解一些關於MVC,並且在使用Ninject時遇到了一個問題。我想綁定存儲庫,但不斷收到'對象引用未設置爲對象的實例'錯誤。ASP MVC 2 Ninject
我創建了我NinjectControllerFactory:
public class NinjectControllerFactory : DefaultControllerFactory
{
// A Ninject "kernel" is the thing that can supply object instances
private IKernel kernel = new StandardKernel(new SportsShopServices());
// ASP .NET MVC calls this to get the controller for each request
protected override IController GetControllerInstance(RequestContext context, Type controllerType)
{
if (controllerType == null)
return null;
return (IController) kernel.Get(controllerType);
}
// Configure how abstract sevice types are mapped to concrete implementations
private class SportsShopServices : NinjectModule
{
public override void Load()
{
Bind<IProductRepository>().To<SqlProductsRepository>()
.WithConstructorArgument("connectionString",
ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString);
}
}
}
和我的控制器:
public class ProductsController : Controller
{
private IProductRepository productsRepository;
// Constructor used with Ninject
public ProductsController(IProductRepository _productsRepository)
{
this.productsRepository = _productsRepository;
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
我已經修改了Web.config文件,以提供數據庫連接字符串和Global.asax文件的Application_Start( )方法包括:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
我正在做一個實例e來自PRO ASP .NET MVC 2的書,但是不能完成這項工作,一直在嘗試。
你嘗試重新建立以下?另外,你的解決方案中是否有類「SqlProductsRepository」? – donhack 2011-02-10 16:01:25
是啊,試圖重建。 SqlProductsRepository在那裏,它用於從數據庫構建並返回一個產品表。 – Apollo 2011-02-10 16:08:32