Search code examples
c#configurationconsole-application.net-7.0

c# Configuration --> query and obtain values for a multi-tenant appsettings.json


I'm working with a multi-tenant appsettings.json and I want to know how to get a list of features by the tenantID based on the below appsettings.json configuration

"Multitenancy": {
    "Tenants": [
      {
        "Name": "Tenant1",
        "TenantId": "21341234-2134-2134-2134-123412342134",
        //other settings in here
        "Features": {
          "FeatureName1": true,
          "FeatureName2": true,
          "FeatureName3": false,
          "FeatureName4": true,
          "FeatureName5": false,
          "FeatureName6": true,
        },
        //more settings
     },
     {
        "Name": "Tenant2",
        "TenantId": "12341234-2134-1234-1234-123412341234",
        //other settings in here
        "Features": {
          "FeatureName1": true,
          "FeatureName2": true,
          "FeatureName3": false,
          "FeatureName4": true,
          "FeatureName5": false,
          "FeatureName6": true,
        },
        //more settings
    }
  ]
}

I have a features class with each feature name and boolean setting created, I'm trying to do a

Features TenantFeatures = Configuration.GetSection("MultiTenant:Tenants:Features").GetChildren().Bind();

where multiTenant.tenants.ID = 21341234-1234-2134-1234-123412342134

I'm a bit stuck, any advice?


Solution

  • You can just bind against a configuration by using IConfiguration.Bind<T>(). Documentation

    Model Classes


    public class Tenant 
    {
        public string Name {get;set;}
        public IDictionary<string, bool> Features {get;set;} = new Dictionary<string, bool>();
    }
    
    public class AppSettings {
        public Multitenancy Multitenancy { get;set;}
    }
    
    public class Multitenancy {
        public IEnumerable<Tenant> Tenants { get;set; } = Array.Empty<Tenant>();
    }
    

    Binding IConfiguration


    var options = config.Get<AppSettings>();
            foreach(var tenant in options.Multitenancy.Tenants)
            {
                Console.WriteLine(tenant.Name);
                
                foreach(var feature in tenant.Features)
                {
                    Console.WriteLine($"{feature.Key}: {feature.Value}");
                }
            }
    

    Here you can find a small working example