Ninject条件结合基于属性值 [英] Ninject conditional binding based on property value

查看:168
本文介绍了Ninject条件结合基于属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ninject具有限定麻烦绑定。

I am having trouble defining bindings using ninject.

我是一个标准的ASP.NET的WebForms应用程序。我已经定义了一个HTTP处理程序注入的页面和控件(属性注入)。

I am in a standard ASP.NET WebForms application. I have defined an http handler to Inject dependencies in pages and controls (Property injection).

下面是我想要做什么:

我创建一个自定义的组合框用户控件。基于在该组合框枚举的价值,我希望能够注入不同的对象中的属性(我所试图做的是更复杂的比这一点,但回答这应该是足以让我去)。

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).

推荐答案

一个条件的基础上的属性值绑定是不是一个很好的设计,甚至是不可能的(至少在构造函数注入)的依赖关系之前,通常创建接受他们的对象。如果该属性是后来改什么?在preferable的办法就是注入,从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.

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)

另外添加活化作用和手动注入的依赖。但要知道,改变约束属性将导致不一致的状态。

Alternatively add an activation action and inject the dependency manually. But be aware that changing the constraint property will lead to an inconsistent state.

OnActivation((ctx, instance) => 
    instance.MyStrategy = ctx.Kernel.Get<MyDependency>(m => 
        m.Get("MyConstraint", null) == instance.MyConstraint);

这篇关于Ninject条件结合基于属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆