Mar*_*tin 5 .net asp.net ninject-2
我无法使用ninject定义绑定.
我在标准的ASP.NET WebForms应用程序中.我已经为页面和控件中的Inject依赖项定义了一个http处理程序(Property injection).
这是我想要做的:
我正在创建一个自定义组合框usercontrol.根据组合框中枚举的值,我希望能够在属性中注入一个不同的对象(我想要做的是比这更多的参与,但对此的回答应该足以让我走).
Rem*_*oor 10
基于属性值的条件绑定不是一个好的设计,甚至不可能(至少对于构造函数注入),因为依赖关系通常在接收它们的对象之前创建.如果以后更改房产怎么办?最好的方法是注入一个从Ninject请求实例的工厂或工厂方法,并在内部交换初始化和属性值更改的策略.
public enum EntityType { A,B }
public class MyControl : UserControl
{
[Inject]
public Func<EntityType, IMyEntityDisplayStrategy> DisplayStrategyFactory
{
get { return this.factory; }
set { this.factory = value; this.UpdateEntityDisplayStrategy(); }
}
public EntityType Type
{
get { return this.type; }
set { this.type = value; this.UpdateEntityDisplayStrategy(); };
}
private UpdateEntityDisplayStrategy()
{
if (this.DisplayStrategyFactory != null)
this.entityDisplayStrategy = this.DisplayStrategyFactory(this.type);
}
}
Bind<Func<EntityType, IMyEntityDisplayStrategy>>
.ToMethod(ctx => type =>
type == ctx.kernel.Get<IMyEntityDisplayStrategy>( m =>
m.Get("EntityType", EntityType.A));
Bind<IMyEntityDisplayStrategy>.To<AEntityDisplayStrategy>()
.WithMetadata("EntityType", EntityType.A)
Bind<IMyEntityDisplayStrategy>.To<BEntityDisplayStrategy>()
.WithMetadata("EntityType", EntityType.B)
Run Code Online (Sandbox Code Playgroud)
或者,添加激活操作并手动注入依赖项.但请注意,更改约束属性将导致状态不一致.
OnActivation((ctx, instance) =>
instance.MyStrategy = ctx.Kernel.Get<MyDependency>(m =>
m.Get("MyConstraint", null) == instance.MyConstraint);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2743 次 |
最近记录: |