MVC5,Web API 2和Ninject

Dec*_*lan 72 ninject asp.net-web-api asp.net-mvc-5

我用Web API 2创建了一个新的MVC5项目,然后我从NuGet添加了Ninject.MVC3包.

构造函数注入适用于MVC5控制器,但在尝试将其与Web API控制器一起使用时出现错误.

尝试创建"UserProfileController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.

工作MVC5控制器的构造函数:

public class HomeController : Controller
{
    private IMailService _mail;
    private IRepository _repo;

    public HomeController(IMailService mail, IRepository repo)
    {
        _mail = mail;
        _repo = repo;
    }
}
Run Code Online (Sandbox Code Playgroud)

非工作Web API控制器的构造函数:

public class UserProfileController : ApiController
{
    private IRepository _repo;

    public UserProfileController(IRepository repo)
    {
        _repo = repo;
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是完整的NinjectWebCommon.cs文件:

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

namespace DatingSite.App_Start
{
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;
using DatingSite.Services;
using DatingSite.Data;

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();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
#if DEBUG
        kernel.Bind<IMailService>().To<MockMailService>().InRequestScope();

#else
        kernel.Bind<IMailService>().To<MailService>().InRequestScope();
#endif
        kernel.Bind<SiteContext>().To<SiteContext>().InRequestScope();
        kernel.Bind<IRepository>().To<Repository>().InRequestScope();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Har*_*ari 104

Ninject.Web.WebApi NuGet 刚刚发布.从现在开始,首选解决方案是使用该包.我找不到任何相关的文档,但安装包后一切都适合我.

Install-Package Ninject.Web.WebApi 
Run Code Online (Sandbox Code Playgroud)

安装完成后,Ninject提供了普通的MVC和API控制器实例.

如果你已经安装了Ninject.Web.Common,请确保从NinjectWebCommon.cs保存绑定,让Nuget在安装过程中重写NinjectWebCommon.cs,并在完成时放回绑定.

正如评论中指出的,取决于您的执行上下文,您还需要以下软件包之一:

  • Ninject.Web.WebApi.WebHost
  • Ninject.Web.WebApi.OwinHost
  • Ninject.Web.WebApi.Selfhost

最常见的情况是IIS选择WebHost包.

如果您从头开始创建IIS MVC5 Web应用程序并希望使用Ninject安装以下软件包:

  • Ninject - Ninject核心dll
  • Ninject.Web.Common - Ninject的常见Web功能,例如.InRequestScope()
  • Ninject.MVC5 - MVC依赖注入器,例如.为MVC提供控制器
  • Ninject.Web.Common.WebHost - 当IIS启动Web应用程序时,从Ninject.MVC5注册依赖注入器.如果您不使用IIS,则需要一个不同的包,请在上面查看
  • Ninject.Web.WebApi WebApi依赖注入器例如.为WebApi提供控制器
  • Ninject.web.WebApi.WebHost - 当IIS启动Web应用程序时,从Ninject.Web.WebApi注册依赖注入器.

  • 为了让它与IIS很好地配合,我需要安装Ninject.Web.WebApi.WebHost.这提供了WebActivatorEx和NinjectWebCommon,这似乎是新的WebApi项目所必需的. (50认同)
  • 当我安装软件包时,这并没有提示覆盖任何文件,但是添加Ninject.Web.WebApi和Ninject.Web.WebApi.WebHost解决了我的组合MVC + Web API应用程序中的问题. (3认同)
  • 不要忘记添加`GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);``RegisterServices(kernel);` (3认同)

Art*_*yan 37

您有这个问题,因为Controller和ApiController使用不同的依赖关系解析器.解决方案非常简单.

首先创建依赖性解析器和依赖性范围的新类.你可以用这个:

 public class NinjectResolver : NinjectScope, IDependencyResolver
{
    private readonly IKernel _kernel;
    public NinjectResolver(IKernel kernel)
        : base(kernel)
    {
        _kernel = kernel;
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(_kernel.BeginBlock());
    }
}

public class NinjectScope : IDependencyScope
{
    protected IResolutionRoot resolutionRoot;
    public NinjectScope(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }
    public object GetService(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).SingleOrDefault();
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).ToList();
    }
    public void Dispose()
    {
        IDisposable disposable = (IDisposable)resolutionRoot;
        if (disposable != null) disposable.Dispose();
        resolutionRoot = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

之后,在NinjectWebCommon中向方法CreateKernel()添加下一行

 GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
Run Code Online (Sandbox Code Playgroud)

  • 我强烈建议使用现在的nuget包.代码与上面的代码有问题 (2认同)

小智 29

我有同样的问题.安装以下NuGet包之后:

  • Ninject
  • Ninject.web.WebApi
  • Ninject.web.WebApi.WebHost
  • Ninject.MVC3
  • Ninject.web.Common
  • Ninject.web.Common.WebHost

一切正常

  • +1谢谢!我没有安装"Ninject.web.WebApi.WebHost",在你发布后我做了.Eveything现在好了. (8认同)
  • 我还需要添加`Ninject.web.WebApi.WebHost`感谢您的帮助! (3认同)
  • 这应该标记为答案. (3认同)
  • Ninject.web.WebApi.WebHost创建您需要的所有文件.您只需要在它提供的RegisterServices中编写您的实现.其他答案令人困惑.这是你唯一需要做的事情. (2认同)

小智 24

我发现程序集Ninject.Web.WebApi.dll定义了自己的DependencyResolver并自动在类Ninject.Web.WebApi.WebApiModule中将其注册到内核.

所以我只需添加到NinjectWebCommon.CreateKernel一行......

GlobalConfiguration.Configuration.DependencyResolver = 
    kernel.Get<System.Web.Http.Dependencies.IDependencyResolver>();
Run Code Online (Sandbox Code Playgroud)

最后我的项目有以下依赖项:

  • Ninject 3.2.0
  • Ninject.Web.Common 3.2.0
  • Ninject.Web.WebApi 3.2.4