質問

Autofacでパラメーターを渡すことに頭を悩ませることができません。次のコードは機能しません:

class Config {
    public Config(IDictionary<string, string> conf) {}
}

class Consumer {
    public Consumer(Config config) {}
}

void Main()
{
    var builder = new Autofac.Builder.ContainerBuilder();
    builder.Register<Config>();
    builder.Register<Consumer>();
    using(var container = builder.Build()){
        IDictionary<string,string> parameters = new Dictionary<string,string>();
        var consumer = container.Resolve<Consumer>(Autofac.TypedParameter.From(parameters));
    }
}

スロー:

DependencyResolutionException: The component 'UserQuery+Config' has no resolvable constructors. Unsuitable constructors included:
Void .ctor(System.Collections.Generic.IDictionary`2[System.String,System.String]): parameter 'conf' of type 'System.Collections.Generic.IDictionary`2[System.String,System.String]' is not resolvable.

しかし、次のコードは動作します

IDictionary<string,string> parameters = new Dictionary<string,string>();
var config = container.Resolve<Config>(Autofac.TypedParameter.From(parameters));
var consumer = container.Resolve<Consumer>(Autofac.TypedParameter.From(config));
役に立ちましたか?

解決

Autofacメーリングリストの回答をここで繰り返します:

Resolveに渡されるパラメーターは、 解決しようとしているサービスなので、Configのパラメーターを解決に渡します Consumerの呼び出しは機能しません。 これを回避するには、消費者登録を次のように変更します。

builder.Register((c, p) => new Consumer(c.Resolve<Config>(p))); 

他のヒント

Autofacは、ディクショナリ自体が解決可能なタイプであるという前提で、明らかにConfigクラスのパラメーターを解決しようとしています。私はそれを行う方法に関するautofac構文を知りません。ただし、おそらくConfigタイプを登録するときは、さらに手順を実行する必要があります。 g。新しい辞書を渡すデリゲートをそれに与えます。

残念ながら、AutofacのようなIoCコンテナには、「私の心のモジュールを読んでください」が備わっていません。

あなたがやろうとしているのは、基本的に「ここに含まれるタイプの1つには辞書が必要で、Consumerタイプのサービスが必要だということです」ということです。 正しいことを実行しますか?&quot;。

1つのサービスを解決し、パラメーターを指定すると、そのパラメーターはその特定のサービスで使用されます。コンテナは、そのパラメータ値を依存関係に伝播しようとしません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top