簡體   English   中英

在.net核心類庫中創建靜態設置類

[英]Creating a static settings class in .net core class library

我邀請批評和反饋。 如果願意的話烤。 我在這里所做的事情感覺不對,我想知道為什么。

在.net core中創建靜態設置類,該類可以從appsettings.json文件返回設置。 它確實可以工作,但是它在每次訪問設置時都使用ConfigurationBuilder。

public static class GeneralSettings
{
    private static IConfigurationRoot Configuration = StartConfig();

    private static IConfigurationRoot StartConfig()
    {
        var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

        return configBuilder.Build();
    }

    public static string ContextUserID
    {
        get
        {
            string result = 
                Configuration.GetSection("AppSettings").GetSection("ContextUserID").Value;

            return result;
        }
    }
}

給定以上代碼,您將在每次調用配置時重新構建配置。 您也可以將其設為單例。 而且由於單身人士不好,所以其他事情可能是錯誤的。 您的直覺覺得這是對的!

  1. 除非您知道它們是靜態的,否則請避免使用static類。
  2. 通常,像這樣的常見“輔助”類違反了一個或多個SOLID原則。 (這可能就是為什么您覺得代碼“錯誤”的原因)

閱讀更多有關此類“輔助”類如何不遵循SOLID原則以及本博客文章中的那些原則的更多信息

如果不是static類,而是要利用.NET Core的內置依賴項注入,我們可以輕松地將此抽象化為一些符合SOLID原則的代碼。 當然,這並不能解決您可以在另一個靜態類中使用新的IContextSettings問題,但是可以使您直接在需要ContextUserID地方將此接口用作一等公民 ,而您只需在其中使用依賴項注入即可。您的ControllerPageModel

public interface IContextSettings
{
    string ContextUserID { get; }
}

public class ContextSettings : IContextSettings
{
    private IConfiguration configuration;

    public ContextSettings(IConfiguration configuration)
    {
        this.configuration = configuration;
    }
    public string ContextUserID => configuration.GetSection("AppSettings").GetSection("ContextUserID").Value;
}

用法(RazorPages示例)

public class IndexModel : PageModel
{
    private readonly IContextSettings settings;

    public IndexModel(IContextSettings settings)
    {
        this.settings = settings;
    }
    public IActionResult OnGet()
    {
        var userId = settings.ContextUserID;
        return Page();
    }
}

感覺對...對嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM