Ninject 基于属性值的条件绑定
我在使用 ninject 定义绑定时遇到问题。
我正在使用标准 ASP.NET WebForms 应用程序。我已经定义了一个 http 处理程序来在页面和控件中注入依赖项(属性注入)。
这就是我想要做的:
我正在创建一个自定义组合框用户控件。基于该组合框上枚举的值,我希望能够在属性中注入不同的对象(我想做的事情比这更复杂,但对此的回答应该足以让我继续下去)。
I am having trouble defining bindings using ninject.
I am in a standard ASP.NET WebForms application. I have defined an http handler to Inject dependencies in pages and controls (Property injection).
Here is what I am trying to do:
I am creating a custom combobox usercontrol. Based on the value of an enum on that combobox, I want to be able to Inject a different object in a property (What I am trying to do is a bit more involved than that, but answer to this should be enough to get me going).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
基于属性值的条件绑定不是一个好的设计,甚至不可能(至少对于构造函数注入),因为依赖项通常是在对象接收它们之前创建的。如果以后房产变了怎么办?更好的方法是注入一个从 Ninject 请求实例的工厂或工厂方法,并在内部交换初始化和属性值更改的策略。
或者添加激活操作并手动注入依赖项。但请注意,更改约束属性将导致不一致的状态。
A conditional binding based on a property value isn't a good design and isn't even possible (at least for constructor injection) as dependencies are normally created before the object receiving them. What if the property is changed later? The preferable way is to inject a factory or factory method that requests the instance from Ninject and exchange the strategy on initialization and property value change internally.
Alternatively add an activation action and inject the dependency manually. But be aware that changing the constraint property will lead to an inconsistent state.
我使用的(现在使用 Ninject 3)有点不同,但它对我有用。
我创建了一系列依赖项,并让他们决定是否接受处理请求。例如,如果我有这个案例,
我希望有帮助!
What I'm using (with Ninject 3 now) is a little different but it works for me.
I create an array of dependencies and let them decide if they accept to handle the request or not. For example if I had this case
I hope that helps!