NinjectDependencyResolver fails binding ModelValidatorProvider

ninject dependency resolver
a cyclical dependency was detected between the constructors of two services ninject
ninject web api 2
make sure that the controller has a parameterless public constructor ninject
could not load type ninject web webapi iwebapirequestscopeprovider from assembly ninject web webapi

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

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.

I get the exception in 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 class:

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 class:

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.

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

Any idea?

UPDATE

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

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

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

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" />

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" />

SECOND UPDATE

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

I set Dependency Resolver here:

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

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

So, if I remove WebContainerManager I don't get that cycle.

NinjectDependencyResolver fails binding ModelValidatorProvider, I'm developing an ASP.NET Web Api 2.2 with C#, .NET Framework 4.5.1. After updating my Web.Api to Ninject 3.2.0 I get this error: Error activating  NinjectDependencyResolver fails binding ModelValidatorProvider (4) Be sure that any old Ninject or Ninject.Web.Common.* dlls aren't present in your bin folder.

Be sure that any old Ninject or Ninject.Web.Common.* dlls aren't present in your bin folder.

I had the same issue in my solution after I had uninstalled Ninject.Web.Common, Ninject.Web.Common.WebHost, Ninject.Web.WebApi, and Ninject.MVC5 from Nuget and installed WebApiContrib.IoC.Ninject in order to use GlobalConfiguration.Configuration.DependencyResolver as in your example. I kept the version of Ninject that I already had installed (which was indeed 3.2.2).

The error did not appear when I first made my changes. However, after moving around from a few git branches and back to my current work, I saw the error. The code that had run fine last week was now throwing the same exact error.

It seems that my bin folder had references to the old Ninject.* packages I had removed. Upon deleting those files, my project worked as expected.

After upgrading to Ninject 3.2.2 we get a Cyclic Dependancy , NinjectDependencyResolver fails binding ModelValidatorProvider. 29. I'm developing an ASP.NET Web Api 2.2 with C#, .NET Framework 4.5.1  The author of the original solution mentioned that NinjectMVC overrides any ModelValidatorProviders definitions set in global.asax. There might be some way to overcome the situation, but it seems to be quite complex.

The cyclic dependency is between the classes "NinjectDefaultModelValidatorProvider" and "DefaultModelValidatorProviders".Simply add a binding for "DefaultModelValidatorProviders" on your startup like below:

_kernel.Bind<DefaultModelValidatorProviders>().ToConstant(new DefaultModelValidatorProviders(config.Services.GetServices(typeof (ModelValidatorProvider)).Cast<ModelValidatorProvider>()));

St4k, DependencyResolver = new NinjectDependencyResolver(kernel); method do some binding. To solve this problem I decided that the easiest and cleanest way was to right click on 1) Request for ModelValidatorProvider. Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

In my case it was working just fine in Owin Selfhost context, but not when hosted in IIS. My solution was to remove all Ninject related assemblies from nuget packages except Ninject itself.

Then I wrote my own DependencyResolver class, feel free to leave improvements in the comments.

public class NinjectDepsolver : IDependencyResolver
{
    private IKernel _kernel;

    public NinjectDepsolver(IKernel kernel)
    {
        _kernel = kernel;
    }

    public void Dispose()
    {
        _kernel = null;
    }

    public object GetService(Type serviceType) => _kernel.TryGet(serviceType);

    public IEnumerable<object> GetServices(Type serviceType) => _kernel.GetAll(serviceType).ToArray();

    public IDependencyScope BeginScope() => new DepScope(this);

    class DepScope : IDependencyScope
    {
        private NinjectDepsolver _depsolver;

        public DepScope(NinjectDepsolver depsolver)
        {
            _depsolver = depsolver;
        }

        public void Dispose()
        {
            _depsolver = null;
        }

        public object GetService(Type serviceType) => _depsolver.GetService(serviceType);

        public IEnumerable<object> GetServices(Type serviceType) => _depsolver.GetServices(serviceType);
    }
}

And then in your Owin Configuration method:

var kernel = new StandardKernel();
kernel.Load(<your module classes>);
var httpConfig = new HttpConfiguration();
var httpConfig.DependencyResolver = new NinjectDepsolver(kernel);
var httpConfig.MapHttpAttributeRoutes();

app.UseWebApi(httpConfig);

Web API 2 and ninject, how to make them work together, NinjectDependencyResolver fails binding ModelValidatorProvider. 2014-10-11 c# Translate ninject ISecureDataFormat binding to Autofac. 2018-03-28 c#  The only way I can think of this can happen is when the WebApiModule is not loaded for some reason. If that module is not loaded then there must something be wrong in your App_Start.

This is what worked for me.

uninstall-package Ninject.Web.WebApi.WebHost

The above command uninstalled the version 'Ninject.Web.WebApi.WebHost 3.2.4.0' and the error is gone!!

Just reconfirm, I have installed the same package using the command

install-package Ninject.Web.WebApi.WebHost

and the command installed the package 'Ninject.Web.WebApi.WebHost 3.2.4.0' and the error reappeared.

ninject- Program QA, 2NinjectDependencyResolver fails binding ModelValidatorProviderSep 14 '15. 2​Extension method for a type writing the <T>Dec 21 '13. 1LINQ MVC ViewModel:  The default constructor provides the default value for the repository, while the second constructor lets us provide one. This is fine when we only have a single controller, but in a real-world system we will likely have a number of different controllers, and having the logic for which repository to use spread among all those controllers is going to be a nightmare to maintain or change.

Decos Software Developement Pvt Ltd - spiritualfasr, DependencyResolver = new NinjectDependencyResolver(kernel); return kernel; I get this error: "Error activating ModelValidatorProvider using binding from I'​m trying to follow the sample, but I have a problem with NewtonSoft.Json. With MVC 5 and Web API 2.2 I solved this problem by making sure I included the following NuGet packages: Ninject.MVC5; Ninject.Web.WebApi.WebHost for Web API; This installed other Ninject dependencies and allowed me to RegisterServices through NinjectWebCommon.cs.

ninject ( Ninject ), Clone via HTTPS Clone with Git or checkout with SVN using the repository’s web address.

Comments
  • have you tried uninstalling all the ninject packages and reinstalling them? Make sure you really got the newest version?
  • Yes, I did that and I got the same error.
  • can you upload the mcve as visual studio project on gist/github repo or something like that? I'd like to take a stab at it.
  • as a side note, instead of using WebContainerManager to statically capture the kernel and use as service locator, i would use this approach which supports ctor-injection into the IActionFilter. Also see here
  • where does the 'config' in the config.DependencyResolver come from?
  • @bigerock WebApiConfig.cs will have a method public static void Register(HttpConfiguration config) which is where the above 2 lines of code should go.
  • When I didn't have the Ninject.Web.WebApi.WebHost dependency, it would work locally but not when I published. Thanks!
  • wow, i kept coming back to this SO until I realized that in publishing to Azure I was not removing the old dlls! Under Publish->Settings->File Publish Options you must check "Remove additional files at destination". Otherwise you'll find that everything works in localhost but not on Azure because the Ninject.Web.* are still there.
  • where is config comming from ?
  • config is GlobalConfiguration.Configuration
  • Hello welcome to SO, can you clarify the logic behind your solution and why it works?