使用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));
    }
}

最佳答案

基本上,MvcServiceLocator已经消失了。我想,无论何时制作视频,版本都会不匹配。

herehere有很好的解释。

使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());

08-26 16:39