【问题标题】:how to pass parameters on resolve time in autofac如何在autofac中的解析时间上传递参数
【发布时间】:2020-04-28 10:19:07
【问题描述】:

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

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

事实上,我编写这段代码是为了使用连接字符串参数注入 NoteBookContext。 (即:new NoteBookContext(string connectionstring)

现在,如何在运行时传递参数值?

【问题讨论】:

    标签: c# autofac


    【解决方案1】:

    WithParameter 方法具有接受委托进行动态实例化的重载。

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

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

    请参阅 Autofac 文档中的 Passing Parameters to Register 了解更多详细信息。

    【讨论】:

    【解决方案2】:

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

    例如:

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

    现在,在解决时,我们可以将Consts.MyConnectionStringconncetionstring 值分配给已解决的DBContext

    IContainer container = builder.Build();
    
    NoteBookContext noteBookContext = container.Resolve<DbContext>(
        new NamedParameter(
            "connectionstring", Consts.MyConnectionString
        )
    );
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        相关资源
        最近更新 更多