c# - 可选地使用 Ninject 注入(inject)一个属性

标签 c# .net ninject

使用 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

装饰您的 PerformanceManager

这将防止内核在无法解析 Binder 时抛出激活异常。它会根据需要将您的依赖项设置为 null。

关于c# - 可选地使用 Ninject 注入(inject)一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5151163/

相关文章:

c# - OnPaint 在调整大小时留下痕迹

c# - 使用 XNA 游戏以试用模式进入 Marketplace

c# - 如何将 C# 中的文本框值插入到 Oracle 数据库中

.net - 如何正则表达式在正向前瞻中正确分割整个模式(问号等于)

.net - 我可以仅针对这种特定情况在 Ninject 中指定范围吗?

c# - 如何获取、更新和删除 Windows Azure Pack 自定义资源提供程序的计划服务配额

c# - 如何设置 Canvas.ZIndex 在控件之间绘制黑色面板?

ninject - 为什么从 NuPack 生成的 NinjectMVC3.cs 无法编译? (或者 ASP.NET MVC 3 Beta 中的 MvcServiceLocator 发生了什么?)

.net - 如何指示 Ninject 从其隐式绑定(bind)列表中隐藏类型

c# - Entity Framework 4.0 - 版本控制