❔ Issue with IOptions when using private getter
Hi,
I have an issue using IOptions. I have a config value (let's call it Config1), which is a list of strings. Unfortunately this config value is stored like this: "str1|str2|str3", and I have to manually transform it, so I can use it like a list.
My first idea was to have a property, public string Config1, with no getter, and the setter would do the transformation, and save the data to another property, public IEnumerable<string> RealConfig1. My issue is that if I don't have a getter, or I have private get, the config value won't be bound.
So this works:
public string Config1
{
get;
set;
}
but this doesn't:
public string Config1
{
private get;
set;
}
The values are coming from Azure App Configuration, we use net6.
Do you have any idea why does it not work? I don't want to have these as public, gettable properties, as other devs who are not familiar with the codebase might get into trouble using it later.4 Replies
So you have a class that you inject as part of options, and you read it as
IOptions<class>
?
And this class has a string that represents that config value?
Why not just have a regular property in the class that represents the joined string, and have a seperate property that splits the values, and returns an array of the values?
There's no distinct key unless there is and your pseudo code doesn't have that, so you might aswell return an array
Otherwise I'm very confused why you have a joined configuration like thisI'm also confused by the joined configuration 🙂 btw, it is stored in a csv file, and is published by a terraform script, there's no chance we can change it
I just realized that there is a BindNonPublicProperties options, when configuring it, so I made those properties private, and access them by a different, public property,
no it looks like this:
private string Config1 { get; set; }
private IEnumerable<string> _realConfig1;
public IEnumerable<string> RealConfig1
{
get
{
if (_realConfig1 is null)
{
_realConfig1 = ... do the transformation ...
}
return _realConfig1;
}
}
So
Config1
has the joined configuration and _realConfig1
has the joined configuration? I guess this is fine
I'd advice you enable nullabillity and change the config to this with it:
This ensures you don't have any caveats with missing data
(Untested, and the throw only works on .NET 7 and later)Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.