2

これが私がやりたいことです:

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;
    }
}

しかし、何も注入されません。私が作業する唯一の方法は、属性と暗黙的な実装を使用することです:

private class Foo : IInject<Bar>
{
    public Bar Bar { get; private set; }

    [Inject]
    public void Inject(Bar reference)
    {
        Bar = reference;
    }
}

それを行う方法はありますか?

4

1 に答える 1

2

デフォルトでは、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;
        }
    }
}

単純にカーネルに追加され、

standardKernel.Components.Remove<ISelector, Selector>();
standardKernel.Components.Add<ISelector, ExplicitSelector>();

そしてIInject<Bar>、カスタムセレクターを使用して、あなたが説明したように意志を取得するための呼び出しが機能します。


* NInject でこれを実装するためのより良い拡張ポイントがあるかもしれません。私は NInject やその実装の専門家にはほど遠いです。

于 2016-11-26T18:31:15.947 に答える