Ninject WCF:属性注入
我正在使用 Ninject WCF 扩展项目在我的 Web 服务上进行依赖项注入。如果我向 Web 服务添加属性(例如 IServiceBehavior),如何在运行时创建该属性时将依赖项注入到该属性中?
I am using the Ninject WCF extension project to do dependency injection on my web service. If I add an attribute to my web service (such as a an IServiceBehavior), how can I inject dependencies into that attribute when it is created at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
属性由 .NET 运行时创建。因此,它们没有真正的依赖注入。您应该尽可能避免拥有需要依赖关系的属性。您有以下选择:
我会尝试使用第一个选项。
Attributes are created by the .NET Runtime. Therefore there is no real dependency injection for them. You should try to avoid having attributes that require dependencies whenever possible. You have the following options:
I'd try to go with the first option.
我不同意属性不应具有依赖关系。通常,验证属性会有不可避免的依赖性。如果正确使用,属性是 DRY 的一个很好的例子。
@wllmsaccnt 采用的方法本质上是 KernelContainer 方法,该方法在 2.2 中被删除 - 但更糟糕。现在该属性已耦合到 WCF 应用程序。
在我看来,这正是我不同意删除 KernelContainer 的原因。我肯定更喜欢注入而不是服务定位器,但我真的不明白为什么当您在无法更改或控制的系统中工作时不鼓励使用服务定位器。
这肯定比为每个应用程序编写额外的自定义代码要好,因为后者很可能比 ServiceLocator 更难维护和更难测试。
I disagree that attributes should not have dependencies in them. Often times validation attributes will have unavoidable dependencies. Attributes are an excellent example of DRY when used correctly.
The approach @wllmsaccnt took is essentially the KernelContainer approach which was removed in 2.2 - but worse. Now the attribute is coupled to the WCF app.
IMO this is precisely the reason I disagree with the removal of the KernelContainer. I'd definitely prefer injection over service locator, but I really don't see why service locator is discouraged when you are working within systems that you can't change or control.
It's surely better than writing additional custom code - for every application - that is most likely less maintainable and less testable than ServiceLocator.