将模块属性注入到动态注册的组件中

时间:2021-07-23 02:34:01

标签: c# autofac .net-5 autofac-configuration autofac-module

使用 autofac json 配置注册模块时,您可以传入属性和/或参数。

{
  "modules": [
    {
      "type": "MyProject.Core.MyModule, MyProject.Core",
      "properties": {
        "ModuleProperties": {
          "prop1": "value1",
          "prop2": "value2"
        }
      }
  ]
}
public class MyModule : Autofac.Module
{
    public Dictionary<string, string> ModuleProps { get; set; }

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<MyType>.As<IMyInterface>();
    }
}

有没有办法将 ModuleProps 传递给我刚刚注册的类型?

1 个答案:

答案 0 :(得分:0)

所以我想通了。我的音乐会类型 MyType 有一个带有 Dictionary<string, string> config 参数的构造函数,当我注册该类型时,我可以像 builder.RegisterType<MyType>.As<IMyInterface>.WithParameter("config", Config) 一样传入它。

相关问题