c# - .net core 2.2 中初始化设置的正确方法?

标签 c# asp.net-core .net-core asp.net-core-mvc asp.net-core-2.2

我创建了一个 REST api 应用程序,它有许多设置并存储在数据库中。这些设置在过滤数据并将数据插入表期间使用。

因为我每次需要插入数据时都需要访问设置。我没有从数据库访问设置,而是创建了一个全局设置类,并将所有设置放入该类中。

public static class GlobalSettings
{
    public static string Setting_1;
    public static string Setting_2;
    public static string Setting_3;
    public static string Setting_4;

    public static void Initialize(ISettingsRepo repo)
    {
        try
        {
            var settings = new GSettings(repo);
            Setting_1 = settings.SetSetting_1();
            Setting_2 = settings.SetSetting_2();
            Setting_3 = settings.SetSetting_3();
            Setting_4 = settings.SetSetting_4();
        }
        catch (Exception ex)
        {
            throw new Exception("Error when loading settings.\r\n" + ex.Message);
        }
    }
}

此处ISettingsRepo 是将从数据库加载设置的范围服务。这些函数将初始化属性的设置。

现在要初始化GlobalSettings,我在启动类中使用了配置方法,如下所示。

using (var scope = app.ApplicationServices.CreateScope())
            {
                Settings.GlobalSettings.Initialize(scope.ServiceProvider
                    .GetRequiredService<Data_Repo.Settings.ISettingsRepo>());
            }

现在我可以在 Controller 或 api 中的任何位置使用它并获取设置而无需访问数据库。另外,如果设置更新,我可以随时重新加载 GlobalSettings。但是这个方法正确还是存在内存泄漏问题?

有没有更好的方法来做到这一点?

最佳答案

示例

我的 appsetting.json 具有这样的结构。

"EmailSettings": {
  "MailServer": "",
  "MailPort": ,
  "Email": "",
  "Password": "",
  "SenderName": "",
  "Sender": "",
  "SysAdminEmail": ""
},

我将这样定义我的类

public class EmailSettings
{
  public string MailServer { get; set; }
  public int MailPort { get; set; }
  public string SenderName { get; set; }
  public string Sender { get; set; }
  public string Email { get; set; }
  public string Password { get; set; }
  public string SysAdminEmail { get; set; }
}

这样我们就有了配置结构。我们需要的最后一件事是在 Startup.cs 中注册

services.Configure<EmailSettings>(configuration.GetSection("EmailSettings"));

在服务类中使用它

private readonly IOptions<EmailSettings> _emailSetting;

public EmailSender(IOptions<EmailSettings> emailSetting)
{
  _emailSetting = emailSetting;
}

email.From.Add(new MailboxAddress(_emailSetting.Value.SenderName, _emailSetting.Value.Sender));

关于c# - .net core 2.2 中初始化设置的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786000/

相关文章:

c# - 我想在整数数组的连续子集中找到公共(public)数字的最大频率

c# - 如何在 ASP.NET Core 中默认使用不记名 token 保护所有 Controller ?

c# - 无法从 'Microsoft.AspNetCore.Mvc.ActionResult' 转换为 'System.Collections.Generic.IEnumerable<string>'

entity-framework - 同一数据库中的 Entity Framework 核心多个 DbContext 迁移

angular - ADFS 2016 - OpenID Connect 发现端点的 CORS 问题

c# - 复制/粘贴键绑定(bind)不起作用

c# - 调用异步方法的两种方式。 C#

c# - 有没有办法确保 Orleans Grains 最终进入同一个筒仓

c# - ASP.NET Core 2.0 中 RequiredAttribute 的本地化

c# - 库中的 AutoMapper 配置文件类 - AutoMapperMappingException : Missing type map configuration or unsupported mapping error