How do I access Configuration in any class in ASP.NET Core?

前端 未结 11 1704
梦如初夏
梦如初夏 2020-11-29 01:09

I have gone through configuration documentation on ASP.NET core. Documentation says you can access configuration from anywhere in the application.

Below is Startup.c

11条回答
  •  被撕碎了的回忆
    2020-11-29 01:24

    The right way to do it:

    In .NET Core you can inject the IConfiguration as a parameter into your Class constructor, and it will be available.

    public class MyClass 
    {
        private IConfiguration configuration;
        public MyClass(IConfiguration configuration)
        {
            ConnectionString = new configuration.GetValue("ConnectionString");
        }
    

    Now, when you want to create an instance of your class, since your class gets injected the IConfiguration, you won't be able to just do new MyClass(), because it needs a IConfiguration parameter injected into the constructor, so, you will need to inject your class as well to the injecting chain, which means two simple steps:

    1) Add your Class/es - where you want to use the IConfiguration, to the IServiceCollection at the ConfigureServices() method in Startup.cs

    services.AddTransient();
    

    2) Define an instance - let's say in the Controller, and inject it using the constructor:

    public class MyController : ControllerBase
    {
        private MyClass _myClass;
        public MyController(MyClass myClass)
        {
            _myClass = myClass;
        }
    

    Now you should be able to enjoy your _myClass.configuration freely...

    Another option:

    If you are still looking for a way to have it available without having to inject the classes into the controller, then you can store it in a static class, which you will configure in the Startup.cs, something like:

    public static class MyAppData
    {
        public static IConfiguration Configuration;
    }
    

    And your Startup constructor should look like this:

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        MyAppData.Configuration = configuration;
    }
    

    Then use MyAppData.Configuration anywhere in your program.

    Don't confront me why the first option is the right way, I can just see experienced developers always avoid garbage data along their way, and it's well understood that it's not the best practice to have loads of data available in memory all the time, neither is it good for performance and nor for development, and perhaps it's also more secure to only have with you what you need.

提交回复
热议问题