C# 是否可以使用Ninject注入显式实现的方法?
以下是我想做的:C# 是否可以使用Ninject注入显式实现的方法?,c#,attributes,ninject,explicit-interface,C#,Attributes,Ninject,Explicit Interface,以下是我想做的: public interface IInject<in T> { [Inject] void Inject(T reference); } private class Foo : IInject<Bar> { public Bar Bar { get; private set; } void IInject<Bar>.Inject(Bar reference) { Bar = ref
public interface IInject<in T>
{
[Inject]
void Inject(T reference);
}
private class Foo : IInject<Bar>
{
public Bar Bar { get; private set; }
void IInject<Bar>.Inject(Bar reference)
{
Bar = reference;
}
}
公共接口输入
{
[注入]
无效注入(T参考);
}
私人类Foo:IInject
{
公共条{get;private set;}
无效注入(条形参考)
{
棒=参考;
}
}
但并没有注入任何东西,我工作的唯一方法是使用属性和隐式实现:
private class Foo : IInject<Bar>
{
public Bar Bar { get; private set; }
[Inject]
public void Inject(Bar reference)
{
Bar = reference;
}
}
私有类Foo:IInject
{
公共条{get;private set;}
[注入]
公共图书馆(酒吧参考)
{
棒=参考;
}
}
有办法吗?默认情况下,Ninject不会这样做。您需要创建一个自定义选择器* 根据您的类型,此选择器显示您描述的行为
class ExplicitSelector : Selector
{
public ExplicitSelector(
IConstructorScorer constructorScorer,
IEnumerable<IInjectionHeuristic> injectionHeuristics)
: base(constructorScorer, injectionHeuristics)
{
}
public override IEnumerable<MethodInfo> SelectMethodsForInjection(Type type)
{
// Gets all implemented interface and grabs an InterfaceMapping.
var implementedInterfaces = type.GetInterfaces();
foreach (var map in implementedInterfaces.Select(type.GetInterfaceMap))
{
for (var i = 0; i < map.InterfaceMethods.Length; i++)
{
// Check each interface method for the Inject attribute, and if present
if (map.InterfaceMethods[i].CustomAttributes.Any(x => x.AttributeType == typeof (InjectAttribute)))
{
// return the target method implementing the interface method.
yield return map.TargetMethods[i];
}
}
}
// Defer to NInject's implementation for other bindings.
foreach (var mi in base.SelectMethodsForInjection(type))
{
yield return mi;
}
}
}
类显式选择器:选择器
{
公共显式选择器(
i构造函数corer构造函数corer,
IEnumerable注入(启发式)
:base(构造函数检索器、注入启发式)
{
}
公共重写IEnumerable SelectMethodsForInjection(类型)
{
//获取所有实现的接口并获取接口映射。
var implementedInterfaces=type.GetInterfaces();
foreach(implementedInterfaces.Select(type.GetInterfaceMap))中的变量映射
{
对于(变量i=0;ix.AttributeType==typeof(InjectAttribute)))
{
//返回实现接口方法的目标方法。
收益率-收益率图.TargetMethods[i];
}
}
}
//对于其他绑定,请遵循NInject的实现。
foreach(基中的var mi.SelectMethodsForInjection(类型))
{
收益率;
}
}
}
它被简单地添加到内核中
standardKernel.Components.Remove<ISelector, Selector>();
standardKernel.Components.Add<ISelector, ExplicitSelector>();
standardKernel.Components.Remove();
standardKernel.Components.Add();
然后调用以获取iInput
将使用自定义选择器按照您所描述的方式工作
*使用NInject实现这一点可能有更好的扩展点。我远不是NInject或其实现方面的专家。问题中缺少的是为什么要这样做。方法注入通常不是一个好主意,因为它会导致成员注入令人讨厌。我继承了一个多毛的图形,由于周期的原因,它对IoC不友好。希望在将设计重构为更好的设计时,这样做只是暂时的。