I'm trying to get the options pattern working with Xml. Here is what I've done so far :
public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration)
{
_logger = logger;
Configuration = configuration;
var mySettings = new MySettings();
Configuration.GetSection(nameof(MySettings)).Bind(_mySettings);
var xmlSettings = new XmlSettings.ConfigurationOptions.configuration();
Configuration.GetSection(nameof(MySettings)).Bind(xmlSettings);
var xmlSettings2 = new XmlSettings.ConfigurationOptions.configuration();
Configuration.GetSection("configuration").Bind(xmlSettings);
}
In my program.cs :
config.AddXmlFile(@"C:\temp\web.config", optional: true, reloadOnChange: true);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
My appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"MySettings": {
"MyJsonSetting": "myJsonValue1234"
}
}
My web.config :
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<MySettings>
<basicSetting>SometBasicSetting</basicSetting>
</MySettings>
</configuration>
My JSON POCO:
public class MySettings
{
public string MyJsonSetting { get; set; }
}
And then finally my Xml class :
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class configuration
{
private configurationMySettings mySettingsField;
/// <remarks/>
public configurationMySettings MySettings
{
get
{
return this.mySettingsField;
}
set
{
this.mySettingsField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class configurationMySettings
{
private string basicSettingField;
/// <remarks/>
public string basicSetting
{
get
{
return this.basicSettingField;
}
set
{
this.basicSettingField = value;
}
}
}
When runing this, I get the JSON settings object populated, as expected, but not the Xml. I have a feeling that the structure of my Xml class isn't correct.
Is what I want to do possible at all, and if so, what am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire