Nate Diamond
Nate Diamond

Reputation: 5575

Abstract Settings Configuration in ASP.NET Core

I have an ASP.NET Core application which can have components of different types. These types are not know until runtime. I have a set of settings which are in a taxonomy of types, and a top-level settings object that stores a collection of the configured components. E.g.,

public class ServiceSettings
{
    List<ComponentSettingsBase> Components { get; set; }
}

public abstract class ComponentSettingsBase
{
}

public class ASettings : ComponentSettingsBase { get; set; }
public class BSettings : ComponentSettingsBase { get; set; }

Using a Json file, I can create the base ServiceSettings object and map it correctly for simple types like strings. When it comes to the collection it just ignores it. I've tried adding type information like Json.NET (Newtonsoft) does for type name handling, but haven't found anywhere to configure how it should be deserialized. I thought that's what they used to use, and there are easy configuration settings for the Json serializer used for Web API communication, but this does not seem to effect the settings/configuration serialization.

Is there a way that I can do this using the built-in settings provider? Or will I need to do something like use the settings provider to point to another file, then use a more fully-fledged Json deserializer to deserialize the settings?

Upvotes: 0

Views: 580

Answers (1)

Zoltan David
Zoltan David

Reputation: 241

I think the problem here is that you want to map a JSON array to a C# List<T>.

What I would do is to change my code to something like this:

public class ServiceSettings
{
    ComponentSettingsBase[] Components { get; set; }
}

I might be wrong, however... Next thing I would try is to go the other direction and

  • build an example object model in memory
  • serialize it to a JSON
  • see how that JSON looks like to learn the format your environment likes
  • reproduce what you need in the format you have learned in the previous step

Upvotes: 2

Related Questions