Skip to content

Cannot create instance of type 'X' because parameter 'XParameter' has no matching config. Each parameter in the constructor that does not have a default value must have a corresponding config entry. #77660

Closed

Description

@navneet10sep

I am deserializing an immutable object that has parameterized constructor with [JsonConstructor] attribute.

     public class DataCenter
    {
        [JsonConstructor]
        public DataCenter(
             List<DataCenterLocation> dataCenterLocations
        )
        {
            this.DataCenterLocations = dataCenterLocations;
        }

        
        public List<DataCenterLocation> DataCenterLocations { get; }
    }

Sample Json Data

{
  "dataCenter": {
    "dataCenterLocations": [
      {
        "name": "United States"
      }
    ]
  }
}

**Facing error in using immutable type with System.Text.Json **

using Microsoft.Extensions.Configuration;
 
IConfigurationRoot configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("datacenter.json", optional: false)
  .Build();

// Error
 var dataCenter = configuration.GetSection("dataCenter").Get<DataCenter>();

foreach (var location in  dataCenter.DataCenterLocations)
{
    Console.WriteLine(location.Name);
}

As mentioned in the >NET documentation the parameter names of a parameterized constructor must match the property names. Matching is case-insensitive, and the constructor parameter must match the actual property. In the above code example

        [JsonConstructor]
        public DataCenter(
             // [JsonPropertyName("dataCenterLocations")] // Doesn't work either 
             List<DataCenterLocation> dataCenterLocations // Match Perfectly with Json Path dataCenter.dataCenterLocations
        )
        {
            this.DataCenterLocations = dataCenterLocations;
        }

Error Details

System.InvalidOperationException
  HResult=0x80131509
  Message=Cannot create instance of type 'JsonConstructorIssue.DataCenter' because parameter 'dataCenterLocations' has no matching config. Each parameter in the constructor that does not have a default value must have a corresponding config entry.
  Source=Microsoft.Extensions.Configuration.Binder
  StackTrace:
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindParameter(ParameterInfo parameter, Type type, IConfiguration config, BinderOptions options)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.CreateInstance(Type type, IConfiguration config, BinderOptions options)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, BindingPoint bindingPoint, IConfiguration config, BinderOptions options)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.Get(IConfiguration configuration, Type type, Action`1 configureOptions)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration, Action`1 configureOptions)
   at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration)
   at Program.<Main>$(String[] args) in D:\lab\JsonConstructorIssue\JsonConstructorIssue\Program.cs:line 16

.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.0-rc.2.22472.3" />
    <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="6.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
  </ItemGroup>

	<ItemGroup>
		<Content Include="./datacenter.json">
			<CopyToOutputDirectory>Always</CopyToOutputDirectory>
		</Content>
	</ItemGroup>

</Project>

I created a GitHub repository to run and test the scenario.

Activity

  1. ghost added
    untriaged
    on Oct 30, 2022
  2. feiyun0112 commented on Nov 1, 2022

    @feiyun0112
    Contributor

    You must use parameter less Constructor, if you want to use NonPublic Set, do like this

    public class DataCenter
    { 
        public List<DataCenterLocation> DataCenterLocations { get; private set; }
    }
    
    var dataCenter = configuration.GetSection("dataCenter").Get<DataCenter>(option => option.BindNonPublicProperties = true);
    
  3. navneet10sep commented on Nov 1, 2022

    @navneet10sep
    Author

    You must use parameter less Constructor, if you want to use NonPublic Set, do like this

    public class DataCenter
    { 
        public List<DataCenterLocation> DataCenterLocations { get; private set; }
    }
    
    var dataCenter = configuration.GetSection("dataCenter").Get<DataCenter>(option => option.BindNonPublicProperties = true);
    

    Parametersless constructor is deserializing private properties using option.BindNonPublicProperties = true but not with the [JsonInclude] attribute as mentioned in the Documentation1 and Documentaiton2

    I could use this workaround for private properties, but not for immutable types. As per my understanding, An immutable type is a type of which its properties can only be set at initialization. Once an object is created, nothing can be changed anymore. So coming back to my original issue, How could I use immutable type as explained in the official documentation ?

  4. added this to the 8.0.0 milestone on Nov 1, 2022
  5. ghost removed
    untriaged
    on Nov 1, 2022
  6. layomia commented on Jul 21, 2023

    @layomia
    Contributor

    This is by design. To have binding succeed when there's a missing config value, specify a default value for your ctor parameter. In this case that would be null:

    public DataCenter(List<DataCenterLocation>? dataCenterLocations = null)
    {
        this.DataCenterLocations = dataCenterLocations;
    }
  7. ghost locked as resolved and limited conversation to collaborators on Aug 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions