所以我使用了Ninject,特别是上下文绑定,如下所示:
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>)
如何根据条件检索实例?
发布于 2012-11-22 22:42:44
得出了答案:最好避免使用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");
然后,您需要创建一个继承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中将其用作:
public class Consumer([FirstProviderConstraint] IBlah)
{
...
}
或者从内核解析
Get<ISession>(metaData => metaData.Get<string>(BindingKeys.Database) == BindingValues.OperationsDatabase)
我需要解决作用域问题,但当您有多个绑定时,这就是如何同时满足构造函数注入和来自内核的显式解析。
https://stackoverflow.com/questions/13510543
复制