Ninject和ASP.NET Web API

Aar*_*zar 11 c# asp.net-mvc ninject

在我提出问题之前,你应该知道我从这个页面得到了我目前的代码:http: //www.strathweb.com/2012/05/using-ninject-with-the-latest-asp-net-web-api -资源/

我正在尝试使用上面站点上的IDependencyResolver适配器在我的应用程序中使用ASP.NET Web API和Ninject.

我创建了所有代码,就像它在网站上显示的一样,但是当我加载我的应用程序时,我的常规控制器失败并显示此错误:

[MissingMethodException: No parameterless constructor defined for this object.]
[InvalidOperationException: An error occurred when trying to create a controller of type 'AccountManager.Controllers.HomeController'...

因此,似乎我可以将Ninject与常规控制器或Web API控制器一起使用,但不能同时使用两者.:(

这是我的代码:

NinjectResolver.cs

public class NinjectResolver : NinjectScope, IDependencyResolver
{
    private IKernel _kernel;

    public NinjectResolver(IKernel kernel)
        : base(kernel)
    {
        _kernel = kernel;
    }

    public IDependencyScope BeginScope()
    {
        return new NinjectScope(_kernel.BeginBlock());
    }
}
Run Code Online (Sandbox Code Playgroud)

NinjectScope.cs

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)

的Global.asax.cs

public class MvcApplication : System.Web.HttpApplication
{
    private void SetupDependencyInjection()
    {
        //create Ninject DI Kernel
        IKernel kernel = new StandardKernel();

        //register services with Ninject DI container
        RegisterServices(kernel);

        //tell asp.net mvc to use our Ninject DI Container
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
    }
}
Run Code Online (Sandbox Code Playgroud)

AccountingController.cs

public class AccountingController : ApiController
{
    private ICustomerService _customerService;

    public AccountingController(ICustomerService service)
    {
        _customerService = service;
    }

    // GET /api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }
}
Run Code Online (Sandbox Code Playgroud)

Yas*_*ser 17

CreateKernel()在调用之前,将以下代码行插入到方法中RegisterServices(kernel);.

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

您还需要使用以下代码,我更喜欢在同一个类中定义它.

public class NinjectResolver : NinjectScope, IDependencyResolver
{
    private 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)

运行它,它应该工作.这对我有用,我希望它也适合你.

进一步阅读:

使用Ninject - 依赖注入与ASP.NET Web API控制器


Pau*_*tti 3

我有一个 Web API 项目,使用与您在 Strathweb 中完全相同的解决方案,因此我只是向该项目添加了一个普通控制器,并且它确实可以工作。它本身对您来说没有多大帮助,所以我将详细介绍我的设置:

我安装了以下软件包(在国际奥委会方面):

  • 忍者3.0.1.10
  • Ninject MVC 3.0.0.6
  • Ninject.Web.Common 3.0.0.7
  • 网络激活器 1.5.1

我的 Global.asax.cs 文件中完全没有关于 Ninject 的内容,而是使用安装 Ninject 时在 App_Start 中自动创建的 NinjectWebCommon.cs 文件。我不知道你的 Global 文件中的代码是否意味着 Ninject 没有在你的项目中正确设置?

以下是 NinjectWebCommon.cs 中的代码:

    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);

        GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(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)
    {
        kernel.Bind<IUserRepository>().To<UserRepository>().InSingletonScope();
        kernel.Bind<IUserManager>().To<UserManager>();
    }        
}
Run Code Online (Sandbox Code Playgroud)

这是我在我们的代码之间看到的另一个区别,我在其中创建了内核,我的代码声明了两个与内核的绑定。

这是我的测试控制器的代码,我可以在构造函数中设置断点并获取它:

public class TestController : Controller
{
    IUserManager _userManager;

    public TestController(IUserManager userManager)
    {
        _userManager = userManager;
    }

    //
    // GET: /Test/
    public ActionResult Index()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

这适用于我的控制器和 API 控制器。