3

Autofac 3.0.0 での登録対象として、次の構造を検討してください。

class Something
{
    public int Result { get; set; }
}

class SomethingGood : Something
{
    private int _good;
    public int GoodResult {
        get { return _good + Result; }
        set { _good = value; }
    }
}

interface IDo<in T> where T : Something
{
    int Calculate( T input );
}

class MakeSomethingGood : IDo<SomethingGood>
{
    public int Calculate( SomethingGood input ) {
        return input.GoodResult;
    }
}

class ControlSomething
{
    private readonly IDo<Something> _doer;
    public ControlSomething( IDo<Something> doer ) {
        _doer = doer;
    }

    public void Show() {
        Console.WriteLine( _doer.Calculate( new Something { Result = 5 } ) );
    }
}

具象型 MakeSomethingGood を登録してから、反変インターフェースで解決しようとしています。

var builder = new ContainerBuilder();
builder.Register( c => new MakeSomethingGood() ).As<IDo<SomethingGood>>();
builder.Register( c => new ControlSomething( c.Resolve<IDo<Something>>() ) ).AsSelf();

var container = builder.Build();
var controller = container.Resolve<ControlSomething>();

...Resolveコンポーネントが見つからないため失敗しますIDo<Something>

私は何を間違っていますか?

ありがとうございました

4

1 に答える 1

1

を登録し、IDo<SomethingGood>を解決しようとしますIDo<Something>。それはどのように機能するはずですか?これが機能するには、IDo<T>を共変として定義する必要があります: IDo<out T>.

IDo<in T>は (キーワードを使用して) 反変として定義されているため、 to をin単純に割り当てることはできません。これは C# ではコンパイルされません:IDo<SomethingGood>IDo<Something>

IDo<SomethingGood> good = new MakeSomethingGood();

// Won't compile
IDo<Something> some = good;

そのため、Autofac はContravariantRegistrationSource.

于 2013-02-07T09:45:50.853 に答える