简体   繁体   English

在 MVC 中调用方法时从 appsettings 创建 object

[英]Creating object from appsettings on method calling in MVC

I'm developing an MVC that connects to multiple CosmosDB databases to perform data cleanup.我正在开发一个连接到多个 CosmosDB 数据库以执行数据清理的 MVC。 It connects based on what method calls the querying method, so the Cosmos connection is built during execution of the query.它根据调用查询方法的方法进行连接,因此 Cosmos 连接是在查询执行期间建立的。 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:我在这里实现了一个帮助程序服务,它应该返回一个 EndpointConfiguration 实例,我将使用它来连接和执行查询:

    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: 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:问题是当我创建 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: 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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