I have the following JSON format in my appsetting:
"AzureServiceBusTopic": {
"TopicsToConsume": [
{
"SubscriptionName": "sub1",
"TopicName": "topic1"
},
{
"SubscriptionName": "sub2",
"TopicName": "topic2"
}
]
}
Currently I'm getting SubscriptionName and TopicName separately:
var topicToConsumeConfig = this.configuration.GetSection("AzureServiceBusTopic:TopicsToConsume").GetChildren();
this.topicToConsume = topicToConsumeConfig.Select(x => x.GetSection("TopicsToConsume").Value);
this.subscriptionName = topicToConsumeConfig.Select(x => x.GetSection("SubscriptionName").Value);
But I need to have the first subscriptionName and topicName together, for the second one likewise. How can I get it?
I want to get these two:
[0]: {
"SubscriptionName": "sub1",
"TopicName": "topic1"
},
[1]: {
"SubscriptionName": "sub2",
"TopicName": "topic2"
}
CodePudding user response:
You can do something like this:
private static List<T> GetList<T>(IConfiguration configuration, string configSection, string keyName)
{
var result = new List<T>();
configuration.GetSection($"{configSection}:{keyName}").Bind(result);
return result;
}
then you can call it like this:
var myListOfTopics = GetList<TopicToConsume>(this.configuration, "AzureServiceBusTopic", "TopicsToConsume");
Obviously you need to create a class to hold the "Topic" object like this:
public class TopicToConsume
{
public string SubscriptionName { get; set; }
public string TopicName { get; set; }
}
You might need to reference nuget Microsoft.Extensions.Configuration.Binder
which gives you access to the Bind extension method.
Also notice that because of the object is a json array [] it comes out as a a List.
But in any case with this code you can pull the whole "list of topics" in one single GetSection call
BONUS:
You can use the same technique to bind dictionaries. So you can really get complex with it.
I made it into a static method that can easily be turned into an extension method.
CodePudding user response:
try this
var items = Configuration
.GetSection("AzureServiceBusTopic:TopicsToConsume")
.Get<Dictionary<string, string>[]>()
.Select(l => new { SubscriptionName = l.Values.ElementAt(0),
TopicName = l.Values.ElementAt(1) });
output
[
{SubscriptionName:"sub1",TopicName:"topic1"},
{SubscriptionName:"sub2",TopicName:"topic2"}
]
or if you have some time and space, you can create a class and use typed object
IEnumerable<Names> items = Configuration
.GetSection("AzureServiceBusTopic:TopicsToConsume")
.Get<Dictionary<string, string>[]>()
.Select(l => new Names { SubscriptionName = l.Values.ElementAt(0),
TopicName = l.Values.ElementAt(1) });
class
public class Names
{
public string SubscriptionName { get; set; }
public string TopicName { get; set; }
}