问题描述
我在autofac中编写以下寄存器类型:
I write following register type in autofac:
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));
实际上,我编写了这段代码,用于使用connectionstring参数注入NoteBookContext. (即:new NoteBookContext(string 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?
推荐答案
WithParameter
方法具有一个重载,可以接受委托进行动态实例化.
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);
请参见将参数从 Autofac传递到注册 em>文档以获取更多详细信息.
See Passing Parameters to Register from Autofac documentation for more detail.
这篇关于如何在autofac中传递解析时间参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!