4
votes

With Ninject 2.2, is there any way to optionally inject a property? In a library I am injecting a performance manager as follows:

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

but on many uses of this library I am 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:

Error activating IPerformanceManager No matching bindings are available, and the type is not self-bindable. Activation path: 5) Injection of dependency IPerformanceManager into property PerformanceManager of type PluginDomainManager etc...

OK, fair enough. So instead, I tried binding it to a method that returns NULL:

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

But now it gives the error:

Error activating IPerformanceManager using binding from IPerformanceManager to method Provider returned null. Activation path: 5) Injection of dependency IPerformanceManager into property PerformanceManager of type PluginDomainManager etc...

So an injected property can never be NULL? I find this surprising. Any ideas how to accomplish an optional injected property?

1

1 Answers

5
votes

You should be able to decorate your PerformanceManager with the OptionalAttribute

This will prevent the Kernel from throwing an Activation exception if it cannot resolve the binder. It will set your dependency to null, just as you want.