If desired, enter a property using Ninject

With Ninject 2.2, is there any way to introduce a property? In the library, I introduce a performance manager as follows:

[Inject] public IPerformanceManager PerformanceManager { private get; set; } 

but in many uses of this library I'm not interested in profiling performance, so I want this property to be null. If I don’t declare a binding for IPerformanceManager at all, I get the following error:

IPerformanceManager activation error There are no suitable bindings, and the type is not self-switching. Activation path: 5) Inject IPerformanceManager dependency into the PerformanceManager property of the PluginDomainManager type, etc.

Good, right. So instead, I tried to bind it to a method that returns NULL:

 kernel.Bind<IPerformanceManager>().ToMethod(m => null); 

But now it gives an error:

IPerformanceManager activation error using binding from IPerformanceManager to method Provider returned null. Activation path: 5) Inject IPerformanceManager dependency into the PerformanceManager property of the PluginDomainManager type, etc.

So, the property entered can never be NULL? I find it awesome. Any ideas on how to accomplish an optional nested property?

+4
source share
1 answer

You can decorate your PerformanceManager with OptionalAttribute

This will prevent the kernel from failing to exclude an activation exception if it cannot resolve the binding. It will set your dependency to zero as you need.

+5
source

Source: https://habr.com/ru/post/1341762/


All Articles