使用NuPack插件并安装NInject MVC 3软件包会导致生成的NinjectMVC3.cs
文件中出现以下编译错误。
The name 'MvcServiceLocator' does not exist in the current context
发布的sample video David Ebbo显示working just fine at 09:43。
这是当前生成的类:
public class NinjectMVC3 {
public static void RegisterServices(IKernel kernel) {
//kernel.Bind<IThingRepository>().To<SqlThingRepository>();
}
public static void SetupDependencyInjection() {
// Create Ninject DI Kernel
IKernel kernel = new StandardKernel();
// Register services with our Ninject DI Container
RegisterServices(kernel);
// Tell ASP.NET MVC 3 to use our Ninject DI Container
MvcServiceLocator.SetCurrent(new NinjectServiceLocator(kernel));
}
}
答案 0 :(得分:13)
基本上,MvcServiceLocator
已经消失了。每当制作视频时,我认为版本不匹配。
使Ninject工作的两个步骤如下。将NinjectMVC3
替换为以下内容(我也更改了不必要的名称):
public class NinjectResolver : IDependencyResolver
{
private static IKernel kernel;
public NinjectResolver()
{
kernel = new StandardKernel();
RegisterServices(kernel);
}
public static void RegisterServices(IKernel kernel)
{
//kernel.Bind<IThingRepository>().To<SqlThingRepository>();
}
public object GetService(Type serviceType)
{
return kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return kernel.GetAll(serviceType);
}
}
并将以下行添加到App_Start()
gloabl.asax.cs
DependencyResolver.SetResolver(new NinjectResolver());
答案 1 :(得分:5)
我修复了包并将其上传到Feed。如果你有机会尝试并验证它现在有效,那就太好了。我将Ninject.MVC3的版本从0.1增加到0.2:)
答案 2 :(得分:1)
我刚刚安装了Ninject.MVC3 0.3。我正在使用ASP.NET MVC 3 Beta。
我已将此代码添加到我的Global.asax.cs
文件中:
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IProductRepository>().To<SqlProductRepository>();
}
public void SetupDependencyInjection()
{
IKernel kernel = new StandardKernel();
RegisterServices(kernel);
DependencyResolver.SetResolver(new Ninject.Mvc3.NinjectServiceLocator(kernel));
}
我已将SetupDependencyInjection()
的电话添加到Application_Start()
功能中,因此看起来像这样:
protected void Application_Start()
{
SetupDependencyInjection();
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
IProductRepository
和SqlProductRepository
是我在Models文件夹中创建的类,并且我已经为我的HomeController
添加了构造函数依赖项。这是代码:
private IProductRepository products;
public HomeController(IProductRepository productRepository)
{
products = productRepository;
}
我添加了一些断点并运行了应用程序,它就像一个魅力。希望这会有所帮助。