ASP.NET Core—access Configuration from static clas

2020-05-19 11:42发布

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 easy way to access it. Is this possible?

namespace MyNamespace
{
    public static class Config
    {
        public string Username => Configuration["Username"];
        public string Password => Configuration["Password"];
    }
}

Anywhere else in the app:

string username = Config.Username;
string password = Config.Password;

12条回答
何必那么认真
2楼-- · 2020-05-19 12:15

Personally I like the method used in this link

Essentially it just adding a static field to your options class.

 public class WeblogConfiguration
 {
    public static WeblogConfiguration Current;

    public WeblogConfiguration()
    {
        Current = this;
    }
} 

Then in any static class you can do:

WeblogConfiguration.Current

Simple and very straight forward

查看更多
相关推荐>>
3楼-- · 2020-05-19 12:16

If you are using environment variables as your configuration, you can access the environment variable directly rather than via the configuration object.

using System;

namespace My.Example
{
    public static class GetPaths
    {
        private static readonly string MyPATH = 
            Environment.GetEnvironmentVariable("PATH");

        private static readonly string MySpecialPath =
            Environment.GetEnvironmentVariable("PREFIX_SpecialPath");
        ...
    }
}
查看更多
再贱就再见
4楼-- · 2020-05-19 12:20

Here is a way to obtain the configuration values from a NET.Core page without having to reference these statically but then still being able to pass them to other static functions called from the non-static class.

At the top of your non-static class add this:

private readonly IConfiguration _configuration;

Then in the constructor function bring in the existing configuration as input to the function: IConfiguration configuration

Then assign the configuration to your read only variable inside the constructor function: _configuration = configuration;

Here is an example of what it should look like:

public class IndexModel : PageModel
{
    private readonly IConfiguration _configuration;

    public IndexModel(IConfiguration configuration)
    {
        _configuration = configuration;
    }
}

After this you can reference the configuration in any function in the class by referencing _configuration and can even then pass this on to other static functions that you call from other classes:

public async Task OnGetAsync()
{
    AnotherClass.SomeFunction(_configuration);
}

Then in the called static class I can make use of the configuration values:

public static string SomeFunction(IConfiguration configuration)
{
    string SomeValue = configuration.GetSection("SomeSectionOfConfig")["SomeValue"];
}

I have a class that calls some stored procedures for viewing and amending data and passes parameter values from appsettings.json using this approach.

查看更多
贼婆χ
5楼-- · 2020-05-19 12:21

A slightly shorter version based on the same principle as above...

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
    StaticConfig = configuration;
}

public static IConfiguration StaticConfig { get; private set; }

To use in another static class:

string connString = Startup.StaticConfig.GetConnectionString("DefaultConnection");
查看更多
6楼-- · 2020-05-19 12:22

I agree with mcbowes, it's in the docs, but the first example looks more like what you need...want:

public class Program
{
    public static IConfigurationRoot Configuration { get; set; }
    public static void Main(string[] args = null)
    {
        var builder = new ConfigurationBuilder()
             .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        Configuration = builder.Build();

        Console.WriteLine($"option1 = {Configuration["option1"]}");

        // Edit:
        IServiceCollection services = new ServiceCollection();
        services.AddOptions();
        services.Configure<HelloWorldOptions>(_configuration.GetSection("HelloWorld"));
        // And so on...
    }
}
查看更多
姐就是有狂的资本
7楼-- · 2020-05-19 12:23

You can use Signleton pattern to access your configurations from anywhere

    public class ConnectionStrings
    {
        private ConnectionStrings()
        {
        }
        // property with getter only will not work.
        public static ConnectionStrings Instance { get; protected set; } = new ConnectionStrings();

        public string DatabaseConnection { get; set; }
    }

and in your startup class

    public class Startup
    {
        private readonly IConfiguration configuration;

        public Startup(IConfiguration configuration)
        {
            this.configuration = configuration;
            configuration.GetSection("ConnectionStrings").Bind(ConnectionStrings.Instance);
        }

        public void ConfigureServices(IServiceCollection services)
        {
        }

        public void Configure(IApplicationBuilder app)
        {
        }
    }
查看更多
登录 后发表回答