ASP.NET Core—access Configuration from static class

后端 未结 13 2020
我在风中等你
我在风中等你 2021-02-01 00:27

I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an e

13条回答
  •  一个人的身影
    2021-02-01 00:56

    This has already been said but I'm going to say it.

    I believe .Net Core wants developers to get values through Dependency Inject. This is what I've noticed from my research but I am also speculating a bit. As developers, we need to follow this paradigm shift in order to use .Net Core well.

    The Options Pattern is a good alternative to the static config. In your case, it'll look like this:

    appsettings.json

    {
      "Username": "MyUsername",
      "Password": "Password1234"
    }
    

    SystemUser.cs

    public class SystemUser 
    {
      public string Username { get; set; } = "";
      public string Password { get; set; } = "";
    }
    

    Startup.cs

    services.Configure(Configuration);
    

    And to use the SystemUser class, we do the following.

    TestController.cs

    public class TestController : Controller 
    {
      private readonly SystemUser systemUser;
    
      public TestController(IOptionsMonitor systemUserOptions)
      {
        this.systemUser = systemUserOptions.CurrentValue;
      }
    
      public void SomeMethod() 
      {
        var username = this.systemUser.Username; // "MyUsername"
        var password = this.systemUser.Password; // "Password1234"
      }
    }
    

    Even though we are not using a static class, I think this is the best alternative that fits your needs. Otherwise, you might have to use a static property inside the Startup class which is a scary solution imo.

提交回复
热议问题