how to pass parameters on resolve time in autofac

时间:2016-04-25 08:52:52

标签: c# autofac

I write following register type in autofac:

 builder.RegisterType<NoteBookContext>()
        .As<DbContext>()
        .WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));

In fact I write this code for injecting NoteBookContext with a connectionstring parameter. (ie : new NoteBookContext(string connectionstring))

Now , How can I Pass value of parameter at runtime?

3 个答案:

答案 0 :(得分:5)

The WithParameter method has a overload that accept delegate for dynamic instanciation.

The first argument is a predicate selecting the parameter to set whereas the second is the argument value provider :

builder.RegisterType<NoteBookContext>()
       .As<DbContext>()
       .WithParameter((pi, c) => pi.Name == "connectionstring", 
                      (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);

See Passing Parameters to Register from Autofac documentation for more detail.

答案 1 :(得分:0)

为了在解析时传递连接字符串值,我们首先需要将构造函数的委托传递给Register方法,然后将传递字符串的值传递给NamedParameter进入Resolve方法。

例如:

ContainerBuilder builder = new ContainerBuilder();

builder.Register((pi, c) => new NoteBookContext(pi.Named<string>("connectionstring")))
            .As<DbContext>();

现在,在解决时间上,我们可以将DBContext的{​​{1}}值分配给已解决的conncetionstring

Consts.MyConnectionString

答案 2 :(得分:0)

如果您只是快速地传递一些东西,您不需要做很多/特别的事情,对我来说,我能够传递一个我想被注射的实例。

container.Resolve<IFoo>(new List<Parameter>{ new TypedParameter(something.GetType(), something)});

注意:我知道我传入的内容未在容器中注册。

相关问题