Ninject,WebAPI 2依赖注入不起作用

时间:2016-01-17 10:44:52

标签: dependency-injection ninject asp.net-web-api2

我正在尝试将Ninject集成到我的WebAPI 2项目中,但是我收到了以下错误:

{
    "message": "An error has occurred.",
    "exceptionMessage": "An error occurred when trying to create a controller of type 'BrandController'. Make sure that the controller has a parameterless public constructor.",
    "exceptionType": "System.InvalidOperationException",
    "stackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
    "innerException": {
        "message": "An error has occurred.",
        "exceptionMessage": "Type 'ADAS.GoTango.WebApi.Controllers.BrandController' does not have a default constructor",
        "exceptionType": "System.ArgumentException",
        "stackTrace": "   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
    }
}

我的包配置是:

<package id="Ninject" version="3.2.2.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net45" />
<package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net45" />
<package id="Ninject.Web.WebApi" version="3.2.4.0" targetFramework="net45" />
<package id="Ninject.Web.WebApi.WebHost" version="3.2.4.0" targetFramework="net45" />
<package id="Ninject.WebApi.DependencyResolver" version="0.1.4758.24814" targetFramework="net45" />

我的代码:

public class BrandController : BaseApiController
{
    readonly BrandsBusiness _brandsBusiness;

    public BrandController(BrandsBusiness brandsBusiness)
    {
        _brandsBusiness = brandsBusiness;
    }

    //public BrandController()
    //{
    //    _brandsBusiness = new BrandsBusiness(new BrandEfStore());
    //}

    public IHttpActionResult Get()
    {
        try
        {
            var allActiveBrands = _brandsBusiness.GetAllActiveBrands();
            return Ok(allActiveBrands);
        }
        catch (Exception exception)
        {
            Logger.Error(exception);
            return InternalServerError();
        }
    }

}

和NinjectWebCommon.cs文件是

/// <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>();
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

        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)
{
    var configuration = new HttpConfiguration();
    kernel.Bind<DefaultModelValidatorProviders>().ToConstant(new DefaultModelValidatorProviders(configuration.Services.GetServices(typeof(ModelValidatorProvider)).Cast<ModelValidatorProvider>()));
    kernel.Bind<BrandsBusiness>().ToSelf().InRequestScope();
    kernel.Bind<IBrandManagement>().To<BrandEfStore>().InRequestScope();
}    

我已经尝试过了:

Parameterless constructor error with Ninject bindings in .NET Web Api 2.1

Ninject.ActivationException thrown only on first web request (WebAPI 2, OWIN 3, Ninject 3)

但他们都没有工作。

1 个答案:

答案 0 :(得分:0)

虽然我不了解Ninject,但我想您需要确保调用CreateKernel方法。您通常会在Application_Start中添加global.asax方法。

您可能需要制作CreateKernel方法internalpublic,以便能够从那里打电话。