使用 Ninject 2.2,有什么方法可以选择性地注入(inject)属性吗?在库中,我按如下方式注入(inject)性能管理器:
[Inject]
public IPerformanceManager PerformanceManager
{
private get; set;
}
但是在这个库的许多用途中,我对分析性能不感兴趣,所以我希望这个属性为空。如果我根本不声明 IPerformanceManager 的绑定(bind),我会收到以下错误:
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...
好的,很公平。因此,我尝试将它绑定(bind)到一个返回 NULL 的方法:
kernel.Bind<IPerformanceManager>().ToMethod(m => null);
但现在它给出了错误:
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...
所以注入(inject)的属性永远不能为 NULL?我觉得这令人惊讶。有什么想法可以实现可选的注入(inject)属性吗?
最佳答案
您应该能够使用 OptionalAttribute
这将防止内核在无法解析 Binder 时抛出激活异常。它会根据需要将您的依赖项设置为 null。
关于c# - 可选地使用 Ninject 注入(inject)一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5151163/