ASP.NET Web API - 500内部服务器错误 - Ninject DI

问题描述 投票:-1回答:1

我有一个Aspnet Web API项目。我使用了存储库模式,我想用ninject进行依赖注入,但它不起作用。

Ninject.Web.Common.cs

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ProjectName.API.App_Start.NinjectWebCommon), "Start")]

[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(ProjectName.API.App_Start.NinjectWebCommon), "Stop")]

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);
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(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<IFirstService>().To<ServiceManager>().WithConstructorArgument("firstServiceDAL", new EFFirstDAL());
    }        
}

Ninject.Web.Common类是否正确?因为它不起作用。

我的api的回应;

"Message": "An error has occurred.",
"ExceptionMessage": "An error occurred when trying to create a controller of type 'FirstController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType": "System.InvalidOperationException",

FirstController.cs - 我的控制器的构造函数

public class FirstController : ApiController
{
    private readonly IFirstService _firstService;

    public FirstController(IFirstService firstService)
    {
        this._firstService = firstService;
    }
}

我能做什么 ?

asp.net-web-api dependency-injection ninject repository-pattern
1个回答
0
投票

您似乎没有公共无参数构造函数。您的FirstController必须具有公共的无参数默认构造函数。将以下代码添加到FirstController中。

public FirstController()
{

}

如果你共享你的控制器会更好。

 private static void RegisterServices(IKernel kernel)
 {
    kernel.Bind<IFirstService>().To<FirstService>();
 }
© www.soinside.com 2019 - 2024. All rights reserved.