0
votes

I have ASP.NET Mvc application and I integrated Ninject as I installed this nuget package which updated my code. I added a NinjectWebCommon class to the App_Start folder of my solution. What I did was to register some of my interfaces and their implementations:

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
  kernel.Bind<ITokenManager>().To<TokenManager>();
} 

The problem is that when I try to resolve an instance of this interface:

var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());

var tokenManager = kernel.Get<ITokenManager>();

I get an error. What it says is:

Error activating ITokenManager No matching bindings are available, and the type is not self-bindable. Activation path: 1) Request for ITokenManager

Suggestions: 1) Ensure that you have defined a binding for ITokenManager. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct.

I don't really understand it as all of the tutorials explain the configuration in the exact same way as I did it.

What could be the reason?

1

1 Answers

1
votes

Here you have created a new kernel instance:

var kernel = new StandardKernel();

Here you specify that this kernel instance should look for modules in the current assembly:

kernel.Load(Assembly.GetExecutingAssembly());

In Ninject terms, a module is a class that implements the NinjectModule class. For example a class like this one that you could add to your current assembly:

public class WarriorModule : NinjectModule
{
    public override void Load() 
    {
        Bind<ITokenManager>().To<TokenManager>();
    }
}

In your question you just seem to have showed some RegisterServices method which is quite unclear by whom it is being called and under what circumstances but you cannot possibly expect that this method would get used somehow by your newly instantiated kernel.

You are probably confused because this RegisterServices method is called by an assembly attribute at application startup, but remember that this method operates on a quite different instance of the kernel parameter. In your case you have a completely different instance that you created manually somewhere in your code. So if you expect to be able to properly resolve dependencies from a kernel please make sure that those dependencies are registered in the same kernel instance form which you are expecting to resolve them.