0

I have a custom configuration XML file came with an SDK. I like to use that file without modifying in order to avoid refactoring all the SDK files dependent on.

I tried with .addXMLFile. But, apparently the XML file is not compatible with that. And then I converted the XML file into json and tried with .addJsonFile. But, it didn't work either, I mean there were several errors complaining about null objects. I don't want to ask on this part, maybe on another topic later on.

Therefore, I've decided to use the proven existing working file loading (StreamReader) and mapping (Deserializing) to my custom class(es).

So far so good. But, at this point, I am not sure how to proceed and append this custom configuration to the IConfiguration in Startup.

At least I tried that;

    private readonly IConfiguration _configuration;

    public void ConfigureServices(IServiceCollection services)
    {
      ...
      ICustomConfiguration settings = null;
      settings = Settings.LoadFromFile("MyCustomConfig.xml"); // settings shows proper structure and data after loading here.
      _configuration.Bind("CustomConfigurationFromFile", (CustomConfigurationFromFile)settings);
      services.AddSingleton(settings);
      ...
    }

Although this doesn't give any error or complain I couldn't see my custom configuration within the collections of the _configuration. Either there is a silence error during binding or my understanding from bind is not accurate.

Any input highly appreciated.

Sener
  • 335
  • 4
  • 17

1 Answers1

0

Try options pattern feature.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options?view=aspnetcore-6.0

With this you can inject e.g. an IOptions<YourCustomConfig> instance where it is needed.

Gabor
  • 3,021
  • 1
  • 11
  • 20
  • Yes, in fact that I've started with that options pattern. But, although `.addXmlFile` loads up the file into `IConfiguration`, assigning it to my `CustomConfigurationFromFile` in my service class (controller) causes incompatibilities. This `private readonly CustomConfigurationFromFile_customSettings;` and `IOptions options,` and `_customSettings = options;` leads to `object not set to an instance of an object` due to complex Getter and Setter in class properties. This is why I said that "I don't want to ask on this part, maybe on another topic later on." – Sener Mar 12 '22 at 16:51