简体   繁体   中英

Ninject .ToFactory: Exception: "Exception thrown: 'Ninject.ActivationException' in Ninject.dll"

I instruct Ninject to create a factory on an interface:

this.Bind<IModelFactory>().ToFactory().InSingletonScope();

In this factory interface, I define the factory:

interface IModelFactory
{
    MyClass CreateMyClassFactory(string param1, DateTime param2);
}

I then attempt to use the factory to create a new class:

Class myClass = modelFactory.CreateMyClassFactory(param1, new DateTime(2017,01,01);

... but it throws this exception:

Exception thrown: 'Ninject.ActivationException' in Ninject.dll

Additional information: Error activating string

No matching bindings are available, and the type is not self-bindable.

Activation path:

2) Injection of dependency string into parameter title of constructor of type MyClass

1) Request for HedgeOrderMyClass

Suggestions:

1) Ensure that you have defined a binding for string.

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.

When you instruct Ninject to create a factory on an interface, you are asking it to pull a new copy of the class out of the container, and fill in any missing parameters at runtime.

This is the class we want:

public class MyClass
{

}

As long as there is at least one constructor that accepts a parameter of type string and DateTime , then it will work:

public class MyClass
{
    // If this constructor is missing, then it throws an exception!
    MyClass(string param1, DateTime param2, ISomeOtherInterface someOtherInterface)
    {
    }
}

Ninject knows how to resolve ISomeOtherInterface , so that's no problem (assume we used Bind<>.To<> elsewhere). But how does it resolve string param1 and DateTime param2 ?

The factory method comes to the rescue: it fills in those parameters from the arguments to the factory call, and everything works nicely.

If you run with the debugger, you will see the constructor above getting called, with the same parameters as specified in the factory creation call.

This is a really powerful idea, and avoids having to manually write all of the glue code to create your own factories.

This is how I normally solve the problem with the Ninject.ActivationException:

using Ninject.Extensions.Factory;

// ...

var kernel = new StandardKernel()
kernel.Bind<IMyClass>().ToFactory();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM