Can't get my head around the parameter passing in Autofac, the following code doesn't work:
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));
}
}
that throws:
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.
but the following code does work:
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));
Repeating here the answer from the Autofac mailing list:
The parameters passed to Resolve only related to the direct implementer of the service you're resolving, so passing Config's parameters to the resolve call for Consumer won't work. The way around this is to change your Consumer registration to:
builder.Register((c, p) => new Consumer(c.Resolve<Config>(p)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With