Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac parameter passing and autowiring

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));
like image 977
Carl Hörberg Avatar asked Jul 31 '09 09:07

Carl Hörberg


1 Answers

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))); 
like image 107
Nicholas Blumhardt Avatar answered Sep 30 '22 18:09

Nicholas Blumhardt