带有 WebAPI 2 的 MVC 4 没有默认构造函数错误

本文关键字:默认 构造函数 错误 WebAPI MVC 带有 | 更新日期: 2023-09-27 17:50:59

嗨,我

正在使用MVC4和WebAPI2,我在Ninject中遇到了does not have a default constructor错误(这是ninject上的已知错误(,我使用了NinjectDependencyResolver自定义类和WebApiContrib.Ioc.Ninject nuget来找出此错误。 这是我下面的NinjectWebCommon

我不确定是不是因为我的项目是分层的,所以层就像 我有"CompositionRoot"层,其中添加了Ninject,并将该层引用到我的主Web层。我的项目正在工作,但我的 web api 没有返回 json,请帮助我,如果不解决这个问题,我就无法前进,提前谢谢。

public static class NinjectWebCommon {
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();
    public static void Start() {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }
    public static void Stop() {
        bootstrapper.ShutDown();
    }
    public static IKernel CreateKernel() {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        RegisterServices(kernel);
        GlobalConfiguration.Configuration.DependencyResolver = 
            new NinjectResolver(kernel);
        // I tested using below code as well (NinjectDependencyResolver 
        // is custom class to fix this issue )        
        //GlobalConfiguration.Configuration.DependencyResolver = 
        //    new NinjectDependencyResolver(kernel);
        return kernel;
    }
    private static void RegisterServices(IKernel kernel) {
        kernel.Bind<IUserBusiness>().To<UserBusiness>().InRequestScope();
        kernel.Bind<IUserDataAccess>().To<UserDataAccess>().InRequestScope();
    }        
}

带有 WebAPI 2 的 MVC 4 没有默认构造函数错误

Drax,

此时创建内核时,不应将DependencyResolver分配给全局配置。原因是因为 Start() 方法通常在WebActivator上运行,甚至在 ASP.NET WebAPI 子系统或应用程序启动之前启动。

我的建议是将此依赖项解析器的分配移动到App_Start中的Global.asaxWebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    [...]
    //Dependency Resolver configuration
    config.DependencyResolver = new NinjectResolver((new Boostrapper).Kernel);
    // Configure routes and the rest of WebAPI stuff.
}

并且不要忘记Global.asax(它应该已经存在(:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

看看这是否适合您,请告诉我们。如果没有,请使用您的NinjectResolver代码更新问题。