NinjectDependencyResolver失败绑定ModelValidatorProvider [英] NinjectDependencyResolver fails binding ModelValidatorProvider

查看:661
本文介绍了NinjectDependencyResolver失败绑定ModelValidatorProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.NET Web API 2.2使用C#.NET框架4.5.1。

I'm developing an ASP.NET Web Api 2.2 with C#, .NET Framework 4.5.1.

更新我的W​​eb.Api到Ninject 3.2.0后,我得到这个错误:

After updating my Web.Api to Ninject 3.2.0 I get this error:

Error activating ModelValidatorProvider using binding from ModelValidatorProvider to NinjectDefaultModelValidatorProvider
A cyclical dependency was detected between the constructors of two services.

Activation path:
  3) Injection of dependency ModelValidatorProvider into parameter defaultModelValidatorProviders of constructor of type DefaultModelValidatorProviders
  2) Injection of dependency DefaultModelValidatorProviders into parameter defaultModelValidatorProviders of constructor of type NinjectDefaultModelValidatorProvider
  1) Request for ModelValidatorProvider

Suggestions:
  1) Ensure that you have not declared a dependency for ModelValidatorProvider on any implementations of the service.
  2) Consider combining the services into a single one to remove the cycle.
  3) Use property injection instead of constructor injection, and implement IInitializable
     if you need initialization logic to be run after property values have been injected.

我得到异常 NinjectWebCommon

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)
    {
        var containerConfigurator = new NinjectConfigurator();
        containerConfigurator.Configure(kernel);
    }        
}

NinjectDependencyResolver 类:

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

namespace Matt.SocialNetwork.Web.Common
{
    public class NinjectDependencyResolver : IDependencyResolver
    {
        private readonly IKernel _container;

        public IKernel Container
        {
            get { return _container; }
        }

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

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

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

        public IDependencyScope BeginScope()
        {
            return this;
        }

        public void Dispose()
        {
            // noop
        }
    }
}

NinjectConfigurator 类:

public class NinjectConfigurator
{
    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;
    }

    // Omitted for brevity.
}

但奇怪的是它编译和作品完美,但更新后,它不能正常工作。

The strange thing is it compiles and works perfectly, but after update it doesn't work.

我已经改变了这个公共类NinjectDependencyResolver:的IDependencyResolver,System.Web.Mvc.IDependencyResolver ,但它仍然无法正常工作

I have changed this public class NinjectDependencyResolver : IDependencyResolver, System.Web.Mvc.IDependencyResolver but it still doesn't work.

任何想法?

更新

调试我看​​到异常在 NinjectDependencyResolver 抛出此:

Debugging I see that the exception is thrown in NinjectDependencyResolver here:

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

它运行两次。首页的serviceType IFilterProvider 和第二次的serviceType ModelValidatorProvider ,之后我得到的异常。

It runs twice. First serviceType is IFilterProvider and second time serviceType is ModelValidatorProvider, and after that I get the exception.

这些都是Ninject包,我使用:

These are the Ninject packages that I'm using:

<package id="Ninject" version="3.2.2.0" targetFramework="net451" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net451" />
<package id="Ninject.Web.WebApi" version="3.2.2.0" targetFramework="net451" />

在previous版本为这些组件是:

The previous version for these assemblies were:

<package id="Ninject" version="3.2.2.0" targetFramework="net45" />
<package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net45" />
<package id="Ninject.Web.Common" version="3.2.2.0" targetFramework="net451" />
<package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net45" />
<package id="Ninject.Web.WebApi" version="3.2.0.0" targetFramework="net451" />

第二次修订

我发现这个问题是在这个类:

I have found that the problem is in this class:

public static class WebContainerManager
{
    public static IKernel GetContainer()
    {
        var resolver = GlobalConfiguration.Configuration.DependencyResolver as NinjectDependencyResolver;
        if (resolver != null)
        {
            return resolver.Container;
        }

        throw new InvalidOperationException("NinjectDependencyResolver not being used as the MVC dependency resolver");
    }

    public static T Get<T>()
    {
        return GetContainer().Get<T>();
    }
}

我设置依赖解析器这里:

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

和我使用 WebContainerManager 在从继承的类 ExceptionFilterAttribute

And I use WebContainerManager in a class that inherits from ExceptionFilterAttribute:

public class UnhandledExceptionFilter : ExceptionFilterAttribute
{
    private readonly IExceptionLogHelper excepLogHelper;

    public UnhandledExceptionFilter()
        : this(WebContainerManager.Get<IExceptionLogHelper>()) {}

    public UnhandledExceptionFilter(IExceptionLogHelper exceptionLogHelper)
    {
        this.excepLogHelper = exceptionLogHelper;
    }

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        this.excepLogHelper.LogException(actionExecutedContext);
    }
}

所以,如果我删除 WebContainerManager 我没有得到循环。

推荐答案

我有升级包Ninject后,各种与WebApi2和Ninject初始化悲伤(甚至卸载并删除旧的)。

I was having all sorts of grief with the WebApi2 and Ninject initialization after upgrading the Ninject packages (even uninstalling and deleting the old ones).

具体到你的情况我会删除code的这些行:

Specifically in your case I would remove these lines of code:

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

,因为他们很可能是错误的原因(在NinjectWebCommon.cs和Ninject库处理现在初始化依赖解析器)。

as they are probably the cause of the error (the NinjectWebCommon.cs and Ninject libraries deal with initializing the dependency resolver now).

对于其他人在那里谁跟着我了类似的升级路径。什么工作对我来说是以下内容:

For others out there who followed a similar upgrade path to me. What worked for me was the following:


  • 删除旧的DependencyResolver初始化code(对我来说这是造成你提到在早期版本的Ninject / WebApi2的特定错误,将在WebApiConfig.cs注册这些线路()方法是如何你初始化DependencyResolver ......这不再是这样):

  • Remove the old DependencyResolver initialization code (for me this was causing the specific error you mention as in earlier versions of Ninject/WebApi2, putting these lines in the WebApiConfig.cs Register() method was how you initialized the DependencyResolver...this no longer is the case):

var kernel = new StandardKernel();
config.DependencyResolver = new NinjectDependencyResolver(kernel);


  • 安装Ninject.Web.WebApi.WebHost包。此安装
    NinjectWebCommon.cs文件。对于我来说,只是具有Ninject.Web.WebApi和它的
    依赖关系没有创建这个文件。

  • Install the Ninject.Web.WebApi.WebHost package. This installed the NinjectWebCommon.cs file. For me, just having the Ninject.Web.WebApi and it's dependencies didn't create this file.

    我的安装和工作Ninject套餐,以供参考:

    My installed and working Ninject Packages for reference:

    <package id="Ninject" version="3.2.2.0" targetFramework="net452" />
    <package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net452" />
    <package id="Ninject.Web.Common.WebHost" version="3.2.0.0" targetFramework="net452" />
    <package id="Ninject.Web.WebApi" version="3.2.3.0" targetFramework="net452" />
    <package id="Ninject.Web.WebApi.WebHost" version="3.2.3.0" targetFramework="net452" />
    

    这篇关于NinjectDependencyResolver失败绑定ModelValidatorProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆