Search code examples
c#dependency-injectioninversion-of-controlninject

Ninject: Ignore Inject when not binded anything


I want that Ninject does not throw Exception when there is an [Inject] attribute but that type was not binded before into ninject. Just ignore it or put null on it.
I tried this code on creation of kernel but didn't help:

kernel.Components.RemoveAll<IMissingBindingResolver>();
kernel.Components.Add<IMissingBindingResolver, DefaultValueBindingResolver>();

But when running throws Ninject.ActivationException.


Solution

  • You should decorate it also with [Optional] attribute.

    https://github.com/ninject/Ninject/blob/master/src/Ninject/Attributes/OptionalAttribute.cs