简体   繁体   English

如何将IConfiguration绑定到构造函数中具有参数的类

[英]How to bind IConfiguration to class having parameters in constructor

I am using standard configuration pattern for ASP.NET Core applications and I can not bind configuration to my class as it has construtor with parameters. 我正在为ASP.NET Core应用程序使用标准配置模式,并且无法将配置绑定到我的类,因为它具有带有参数的构造函数。

In appsettings.json I included desired config: 在appsettings.json中,我包含了所需的配置:

    "MyServiceConfig": {
      "Identity": {
        "Version": "1.0",
        "ComplicatedUri": {
          "Scheme": "http",
          "Authority": "localhost",
          "Path": "SuperService"
        }
      }
    },

My config class and it's dependencies look like that: 我的配置类及其依赖项如下所示:

        public class MyServiceConfig
        {
            public MyIdentity Identity { get; set; }
        }

        public class MyIdentity
        {
            public string IdentityName { get; set; }
            public string Version { get; set; }
            public MyComplicatedUri ComplicatedProperty { get; set; }

            public MyIdentity(string version, MyComplicatedUri complicatedProperty)
            {
                Version = version;
                ComplicatedProperty = complicatedProperty;
                IdentityName = complicatedProperty.Path;
            }
        }

        public class MyComplicatedUri
        {
            public string Scheme { get; set; }
            public string Authority { get; set; }
            public string Path { get; set; }
        }

I have already tried code like that: 我已经尝试过这样的代码:

        private MyServiceConfig GetMyConfig(IConfiguration configuration)
        {
            var config = new MyServiceConfig();
            configuration.GetSection("MyServiceConfig").Bind(config);
            return config;
        }

It throws exception: 它引发异常:

'Cannot create instance of type 'MyIdentity' because it is missing
a public parameterless constructor.'

That behaviour can make sense in some cases but in that particular one not so much. 在某些情况下,这种行为可能很有意义,但在特定情况下却没有那么多。 Mappings could be straightforward - by property names which have public setters or by constructor parameter names. 映射可能很简单-通过具有公共设置器的属性名称或构造函数参数名称。

Another idea would be adding converter in AddJsonOptions in Startup class for my types - IConfiguration.Bind could infer how to construct it but I also tried that with no success. 另一个想法是在Startup类的AddJsonOptions中为我的类型添加转换器-IConfiguration.Bind可以推断出如何构造它,但我也尝试了失败。

Have you encoutered similar problems and found some reasonable solution to that? 您是否遇到过类似的问题并找到了合理的解决方案?

Edit: Adding parameterless constructor will work of course, but sometimes I need to deal with some classes from external packages I'd like to use as parts of my config class so let's assume we can not modify them. 编辑:添加无参数构造函数当然可以,但是有时候我需要处理一些我想用作config类的一部分的外部包中的类,所以让我们假设我们无法对其进行修改。 I'd like to avoid adding new types for mapping only as well. 我也想避免只添加用于映射的新类型。 Ideally I'd like to force ASP.NET Core engine to use existing constructor with parameters and by parameter name map with json properties - which currently is not working. 理想情况下,我想强制ASP.NET Core引擎使用带参数的现有构造函数,并按参数名称映射使用json属性-当前不起作用。

You should just add a default constructor in MyIdentity class. 您应该只在MyIdentity类中添加默认构造函数。 .bind() binds the configuration into the object using the default constructor. .bind()使用默认构造函数将配置绑定到对象中。 So, add the required default constructor in your MyIdentity class and it will be fine. 因此,在MyIdentity类中添加所需的默认构造函数,就可以了。

public MyIdentity(){}

Also , you can use Options . 另外 ,您可以使用选项

In ConfigureServices , add the following: ConfigureServices ,添加以下内容:

services.AddOptions();
services.ConfigureOptions<MyServiceConfig>();

and then use dependency injection to initialize it. 然后使用依赖项注入将其初始化。 In addition, use your own JsonConverter 另外,使用您自己的JsonConverter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM