2012-11-22 46 views
0

所以我使用Ninject,特别是上下文绑定,如下所示:Ninject获取<T> WhenTargetHas <T>

Bind<IBlah>().ToMethod(x => FirstBlahProvider.Instance.GiveMeOne()).WhenTargetHas<FirstAttribute>().InRequestScope(); 
Bind<IBlah>().ToMethod(x => SecondBlahProvider.Instance.GiveMeOne()).WhenTargetHas<SecondAttribute>().InRequestScope(); 

我需要使用内核得到一个给定的实例,并希望根据条件做WhenTargetHas<T>。类似下面的东西会很棒。

var myblah = Kernal.Get<IBlah>(x => x.HasWithTarget<FirstAttribute>) 

如何根据条件检索实例?

回答

0

摸索出了答案: 最好避免使用WhenTargetHas<T>改用WithMetaData(key, value)

所以

Bind<IBlah>().ToMethod(x => FirstBlahProvider.Instance.GiveMeOne()).WhenTargetHas<FirstAttribute>().InRequestScope(); 
Bind<IBlah>().ToMethod(x => SecondBlahProvider.Instance.GiveMeOne()).WhenTargetHas<SecondAttribute>().InRequestScope(); 

变为:

Bind<IBlah>().ToMethod(x => FirstBlahProvider.Instance.GiveMeOne()).WithMetaData("Provider", "First); 
Bind<IBlah>().ToMethod(x => SecondBlahProvider.Instance.GiveMeOne()).WithMetaData("Provider", "Second"); 

然后,您需要创建继承Ninject的属性ConstraintAttribute并在构造函数的争论中使用该属性。

由于:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)] 
    public class FirstProviderConstraint : ConstraintAttribute 
    { 
      public override bool Matches(IBindingMetadata metadata) 
      { 
       return metadata.Has("Provider") && metadata.Get<string>("Provider") == "First"; 
      } 
    } 

然后你用它在构造函数中ARG为:

还是从内核解决

Get<ISession>(metaData => metaData.Get<string>(BindingKeys.Database) == BindingValues.OperationsDatabase) 

我需要解决划定范围,但是这是怎么当您有多个绑定时,您同时满足来自内核的构造函数注入和显式解析。

相关问题