如何在autofac中传递有关解析时间的参数

min*_*ali 2 c# autofac

我在autofac中写下以下寄存器类型:

 builder.RegisterType<NoteBookContext>()
        .As<DbContext>()
        .WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));
Run Code Online (Sandbox Code Playgroud)

实际上,我编写了这个代码,用于使用connectionstring参数注入NoteBookContext.(即:new NoteBookContext(string connectionstring))

现在,我怎样才能在运行时传递参数值?

Cyr*_*and 5

WithParameter方法具有一个重载,接受动态实例化的委托.

第一个参数是谓词选择要设置的参数,而第二个参数是参数值提供者:

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

有关更多详细信息,请参阅从Autofac文档传递参数以进行注册.