I am having configuration.ini file which contain following content ->
[Objects]
obj1={7CE7ECE0-B70D-4622-8F4B-D999E5F06AAD}
obj2={5964945B-C31B-4805-9408-D56A4A5457CF}
obj3={5964945B-C31B-4805-9408-D56A4A5457CF}
Those keys - objN can be dynamically added.
With help of ConfigurationBuilder I am creating the config ->
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddIniFile(Path.Combine(configFolderPath, @"Configuration.ini"))
.Build();
Now when it come to the topic of Binding to object I get stuck and cant find any solution.
services.AddOptions<SomeObject>()
.Bind(_configuration.GetSection("Object"))
P.S
As temporary solution I found is to get configuration section as enumerable which is dictionary<string,string>
and then map it manually. This is just look quite dirty.
configuration.GetSection("Objects").AsEnumerable()
CodePudding user response:
I would say Guru Stron gave you the answer.
services.Configure<Dictionary<string, Guid>>(_configuration.GetSection("Objects"));
Then, consume with DI:
public class SomeService
{
private Dictionary<string, Guid> Objects { get; }
public SomeService(IOptions<Dictionary<string,Guid>> objects)
{
Objects = objects.Value;
}
}
If you feel that Dictionary<string,Guid>
is not a specific-enough data type, simply create a derived class:
public class MyObjectDictionary : Dictionary<string, Guid>
{ }
Then use MyObjectDictionary
as the type in the call to services.Configure<>()
.
CodePudding user response:
You should look at using the INI configuration provider for this https://learn.microsoft.com/en-us/dotnet/core/extensions/configuration-providers#ini-configuration-provider
As for dynamic loading, You can use IOptionsSnapshot or IOptionsMonitor.
CodePudding user response:
I think this would be working for you
public class MyClass
{
private readonly Dictionary<string, string> _objects ;
public MyClass(IConfiguration config)
{
_objects=config.GetSection("Objects").Get<Dictionary<string, string>>();
Console.WriteLine(_objects["obj1"]);
}
}