Search code examples
c#jsonautofacautofac-moduleautofac-configuration

Nested list in dictionary property through Autofac.Configuration in JSON


I use Autofac.Configuration but I can't use nested property configuration. The following property NestedListInDictPropThatDoesNotWork is not working:

    "type": "Some.Modules.CoolModule, Some.Modules",
    "properties": {
        "StringProp": "hello world",
        "IntProp": 8090,
        "BoolProp": false,
        "DictProp": { "key": "value" },
        "ListProp": [1, 2, 3, 4, 5],
        "NestedListInDictPropThatDoesNotWork": {
            "myKey": [ "A", "B" ]
        }

Do I have to use an other syntax for that? I want to configure a Dictionary, where the value is a List of items instead of a simple value type.


Solution

  • Note: Cross-posted as an issue to Autofac. Further discussion on implementation or timeline will happen there.

    The configuration library isn't doing full "model binding" to figure out property values. It's a much simpler mechanism using a flatter binding concept - much closer to what the classic XML style configuration supported (more "key/value pair" than "recursive binding").

    You can see how we parse dictionaries here. It's trying type converters and casting on the value.

    To understand why that doesn't "just work," think about how Microsoft.Extensions.Configuration parses this configuration. It's all key/value pairs to that system:

    "type" = "Some.Modules.CoolModule, Some.Modules"
    "properties:StringProp" = "hello world"
    "properties:IntProp" = "8090"
    "properties:BoolProp": "false"
    "properties:DictProp:key": "value"
    "properties:ListProp:0" = "1"
    "properties:ListProp:1" = "2"
    "properties:ListProp:2" = "3"
    "properties:ListProp:3" = "4"
    "properties:ListProp:4" = "5"
    "properties:NestedListInDictPropThatDoesNotWork:myKey:0" ="A"
    "properties:NestedListInDictPropThatDoesNotWork:myKey:1" ="B"
    

    The Autofac configuration stuff does its best to try to "infer" what is meant by each property, but it's not an actual model binder. At the time we originally wrote it, the Microsoft.Configuration.Extensions.Binder stuff wasn't there and when it started getting there, it wasn't quite where we needed it. That may be a better option for us now that .NET Core has settled down a bit.

    We'd be happy to take a pull request with an update for this support. In the meantime, the issue is marked as an enhancement request.