Autofact transfer and auto-connect

Unable to omit around a parameter passing in Autofac, the following code does not 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));
    }
}

which 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 really works:

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));
+5
source share
3 answers

Repeating here the answer from the Autofac mailing list:

The parameters passed to Resolve refer only to the immediate service that you allow, so pass the configuration parameters to resolve the call for the Consumer will not work. To do this, change your registration for users:

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

Autofac, , Config , . autofac , . , , Config, . . , .

0

, IoC, Autofac, ", ".

, , : " , , " ", , ? ?".

If you enable one service and specify a parameter, this parameter will be used for this particular service. The container will not attempt to propagate this parameter value to any dependencies.

0
source

All Articles