Api控制器没有预定义的构造函数

时间:2016-11-29 15:58:40

标签: c# asp.net-web-api ninject

我正在使用.NET Framework 4.6.2开发ASP.NET Web Api 2.2 Web服务。

是的,有很多类似于我的问题但是我在答案中做了他们建议的一切,我有以下错误:

{
  "Message": "Error.",
  "ExceptionMessage": "Error trying to create a controller of type 'PrintedCodesStatisticsController'. Ensure that the controller has a public constructor without parameters.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   en System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   en System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   en System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
  "InnerException": {
    "Message": "Error.",
    "ExceptionMessage": "Type 'MyProject.WebApi.Controllers.PrintedCodesStatisticsController' doesn't have a predefined constructor",
    "ExceptionType": "System.ArgumentException",
    "StackTrace": "   en System.Linq.Expressions.Expression.New(Type type)\r\n   en System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   en System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   en System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
  }
}

我在项目中使用的软件包是:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.3" targetFramework="net462" />
  <package id="log4net" version="2.0.5" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Client.es" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Core.es" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.WebHost.es" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" />
  <package id="Ninject" version="3.2.2.0" targetFramework="net462" />
  <package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net462" />
  <package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net462" />
  <package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net462" />
  <package id="WebActivatorEx" version="2.2.0" targetFramework="net462" />
</packages>

而且我确定我正在使用NinjectDependenciaResolver,因为我已经调试了它并且它停在GlobalConfiguration.Configuration.DependencyResolver上。

NinjectDependencyResolver是:

using Ninject;
using System.Web.Http.Dependencies;

namespace AnotherProject.Web.Common.Ninject
{
    /// <summary>
    /// Used to resolve dependencies.
    /// </summary>
    public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
    {
        public NinjectDependencyResolver(IKernel kernel)
            : base(kernel)
        { }

        public IDependencyScope BeginScope()
        {
            return this;
        }
    }
}

NinjectDependencyScope是:

public class NinjectDependencyScope : IDependencyScope
{
    private readonly IKernel _container;

    public IKernel Container
    {
        get { return _container; }
    }

    public NinjectDependencyScope(IKernel container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        return _container.TryGet(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.GetAll(serviceType);
    }

    public void Dispose()
    {
        // noop
    }
}

最后,NinjectConfigurator是:

public class NinjectConfigurator
{
    /// <summary>
    /// Entry method used by caller to configure the given 
    /// container with all of this application's 
    /// dependencies. Also configures the container as this
    /// application's dependency resolver.
    /// </summary>
    public void Configure(IKernel container)
    {
        // Add all bindings/dependencies
        AddBindings(container);

        // Use the container and our NinjectDependencyResolver as
        // application's resolver
        var resolver = new NinjectDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;
    }

    /// <summary>
    /// Add all bindings/dependencies to the container
    /// </summary>
    private void AddBindings(IKernel container)
    {
        [ ... ]
    }
}

如何解决此错误?

2 个答案:

答案 0 :(得分:1)

注册Ninject IoC容器的方法很少。一种方法是使用 WebActivator。

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(NinjectWebCommon), "Stop")]

您可以在GitHub下载我的示例项目。原始项目适用于MVC,因此您只需要使用以下两行代替第30行和第31行进行Web API。

var resolver = new NinjectDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;

FYI :我的示例项目中有两个主要文件Ninject - NinjectConfigurator.csNinjectWebCommon.cs

答案 1 :(得分:0)

为了使Ninject Dependency Injection框架与ASP.NET WebApi 2.2一起使用.NET Framework 4.6.2,请安装以下软件包,注意Ninject软件包和版本。

Ninject 3.2.0.0
Ninject.MVC5 3.2.1.0
Ninject.Web.Common 3.2.0.0
Ninject.Web.WebApi 3.2.4.0
Ninject.Web.WebApi.WebHost 3.2.4.0

packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.3" targetFramework="net462" />
  <package id="log4net" version="2.0.5" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Client.es" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.Core.es" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebApi.WebHost.es" version="5.2.3" targetFramework="net462" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net462" />
  <package id="Newtonsoft.Json" version="9.0.1" targetFramework="net462" />
  <package id="Ninject" version="3.2.0.0" targetFramework="net462" />
  <package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net462" />
  <package id="Ninject.Web.Common" version="3.2.0.0" targetFramework="net462" />
  <package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net462" />
  <package id="Ninject.Web.WebApi" version="3.2.4.0" targetFramework="net462" />
  <package id="Ninject.Web.WebApi.WebHost" version="3.2.4.0" targetFramework="net462" />
  <package id="WebActivatorEx" version="2.2.0" targetFramework="net462" />
</packages>

以下是位于App_Start中的NijectWebCommon.cs,请确保您在RegisterServices方法中注册的类型已正确注册 例如..

kernel.Bind<IEmployeeRepository>().To<EmployeeRepository>(); instead of
kernel.Bind<IEmployeeRepository, EmployeeRepository>();

NijectWebCommon.cs

using MyData;
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyTestApp.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(MyTestApp.App_Start.NinjectWebCommon), "Stop")]

namespace MyTestApp.App_Start
{


    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }

        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }

        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            try
            {
                kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
                kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

                RegisterServices(kernel);
                return kernel;
            }
            catch
            {
                kernel.Dispose();
                throw;
            }
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IEmployeeRepository>().To<EmployeeRepository>();
        }        
    }
}

以下是示例api控制器

using System.Web.Http;
using MyData;

namespace MyTestApp.Controllers
{
    public class MyTestController : ApiController
    {
        private readonly IEmployeeRepository _employeeRepository;
        public MyTestController(IEmployeeRepository employeeRepository)
        {
            _employeeRepository = employeeRepository;
        }


        public IHttpActionResult Get()
        {
            var employees = _employeeRepository.GetEmployees();
            return Ok(employees);
        }
    }
}