简体   繁体   中英

Creating object from appsettings on method calling in MVC

I'm developing an MVC that connects to multiple CosmosDB databases to perform data cleanup. It connects based on what method calls the querying method, so the Cosmos connection is built during execution of the query. Then it is disposed of after the query has finished executing.

Here I've implemented a helper service should return an instance of the EndpointConfiguration that I will use to connect and perform the query:

    public static class ConfigurationService
    {
        public static EndpointConfiguration GetByName(string configKeyName)
        {
            var environmentName = "Development";

            var config = new ConfigurationBuilder()
                .AddJsonFile($"appsettings.{environmentName}.json")
                .Build();

            var section = config.GetSection("CosmosConnectionStrings");
            var endpointConfiguration = section.Get<EndpointConfiguration>();

            return endpointConfiguration;
        }
    }

Model:

    public class EndpointConfiguration
    {
        public string DatabaseUrl { get; set; }
        public string SourceDatabase { get; set; }
        public string SourceContainer { get; set; }
    }

The problem is that my code doesn't populate the values when I create the object:

public static async Task<List<EventDocument>> GetEventDocsWithQueryAsync(string queryString, [CallerMemberName] string memberName = "")
        {
            string databaseName = ResolveDatabaseFromCallingMethod(memberName); //returns string of "DatabaseCosmosDb1" or "DatabaseCosmosDb2"
            var settings = ConfigurationService.GetByName(databaseName); //always null

            CosmosClient client = new CosmosClient(settings.DatabaseUrl, new CosmosClientOptions()
            {
                ConnectionMode = ConnectionMode.Gateway,
                AllowBulkExecution = true
            });
            Container container = client.GetContainer(settings.SourceDatabase, settings.SourceContainer);
            List<EventDocument> results = new List<EventDocument>();

            using (FeedIterator<EventDocument> resultSetIterator = container.GetItemQueryIterator<EventDocument>(queryString))
            {
                while (resultSetIterator.HasMoreResults)
                {
                    FeedResponse<EventDocument> response = await resultSetIterator.ReadNextAsync();
                    results.AddRange(response);
                }
            }
    
            client.Dispose();
            return results;
        }

appsettings.Development.json:

"CosmosConnectionStrings": {
    "DatabaseCosmosDb1": {
      "DatabaseUrl": "AccountEndpoint=[endpoint]",
      "SourceDatabase": "DatabaseA",
      "SourceContainer": "EventsA"
    },
    "DatabaseCosmosDb2": {
      "DatabaseUrl": "AccountEndpoint=[endpoint]",
      "SourceDatabase": "DatabaseB",
      "SourceContainer": "EventsB"
    }
  }

How can I fix this to get the database connection variables during the method?

This code can be extracted to not run every time

var environmentName = "Development";

var config = new ConfigurationBuilder()
    .AddJsonFile($"appsettings.{environmentName}.json")
    .Build();

Then you need to specify a key of the section

  var section = config.GetSection($"CosmosConnectionStrings:{configKeyName}");
  var endpointConfiguration = section.Get<EndpointConfiguration>();
  return endpointConfiguration;

or

  var section = config.GetSection("CosmosConnectionStrings");
  var endpointConfiguration = section
     .GetSection(configKeyName)
     .Get<EndpointConfiguration>();

  return endpointConfiguration;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM