简体   繁体   English

如何使用.Net 5 Core在其他类中全局访问appsettings.json

[英]How to access appsettings.json globally in other classes using .Net 5 Core

I need access to the appsettings.json configuration in other non-controller classes in my project.我需要访问我项目中其他非控制器类中的 appsettings.json 配置。 Is there a good way for IConfiguration to be available globally throughout my application w/o using DI?有没有一种好方法可以让 IConfiguration 在我的应用程序中全局可用而无需使用 DI? If the IConfiguration DI could be used on non-controller classes, I'd like to know how to do that.如果 IConfiguration DI 可用于非控制器类,我想知道如何做到这一点。

This is my controller where HostService has access to the IConfiguration injection.这是我的 controller,其中 HostService 可以访问 IConfiguration 注入。

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<HostService>();
        }).UseSerilog();
}

I need access to IConfiguration in this non-controller class.我需要访问此非控制器 class 中的 IConfiguration。 I'm not sure how to use the DI w/ non-controller type classes, so maybe using a static type configuration variable would be a better solution to make IConfiguration available globally.我不确定如何使用带有非控制器类型类的 DI,因此使用 static 类型的配置变量可能是使 IConfiguration 全局可用的更好解决方案。

public class myTestClass 
{
    private readonly IConfiguration _config

    public myTestClass(IConfiguration config){ _config = config}
}

You can add a configuration to you DI container by adding a handling of config to you host:您可以通过向主机添加配置处理来向 DI 容器添加配置:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostContext, config) =>
        {
            config.AddJsonFile("appsettings.json", false, false);
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<HostService>();
        })
        .UseSerilog();
}

It makes the whole IConfiguration object available for your application:它使整个IConfiguration object 可用于您的应用程序:

public class TestOptions
{
    public string Data { get; set; }
}

public class HostService : BackgroundService
{
    private readonly IConfiguration _configuration;

    public HostService(IConfiguration config)
    {
        _configuration = config;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        // TODO: write your code here
    }
}

I need access to IConfiguration in this custom class.我需要访问此自定义 class 中的 IConfiguration。 I can pass an IConfiguration instance in from the HostService class, but was looking for global solution to avoid passing instances to other classes.我可以从 HostService class 传递一个 IConfiguration 实例,但正在寻找全局解决方案以避免将实例传递给其他类。

Dependency Injection solves a lot of different issues, and today it is a common way to develop software.依赖注入解决了很多不同的问题,现在它是开发软件的常用方法。 It is much easier to use DI instead of avoid using it.使用 DI 而不是避免使用它要容易得多。

I actually figured out a way to make IConfiguration available throughout the application without using Injections.实际上,我想出了一种方法来使 IConfiguration 在整个应用程序中可用,而无需使用注入。 It's quite pointless to use IConfiguration DI for non-controller classes since it requires too many steps.将 IConfiguration DI 用于非控制器类是毫无意义的,因为它需要太多步骤。 Just create a static class w/ a static IConfiguration variable and assign the Iconfiguration injection parameter to it from the main controller class and it'll be available throughout the app. Just create a static class w/ a static IConfiguration variable and assign the Iconfiguration injection parameter to it from the main controller class and it'll be available throughout the app. It's simple and easy.这很简单。

Programs.cs程序.cs

        public static IHostBuilder CreateHostBuilder(string[] args)
            {
                return Host.CreateDefaultBuilder(args)
                    .UseWindowsService()
                    .ConfigureServices((hostContext, services) =>
                    {
                        services.AddHostedService<HostService>();
                    }).UseSerilog();
            }   
        

HostService.cs主机服务.cs

        public static class AppData
        {
            public static IConfiguration Config;
        }
        public class HostService : IHostedService, IDisposable
        {
            public HostSyncService(IConfiguration config)
            {
                AppData.Config = config;

                var key= new myTestClass().getKey();
            }
        }
        

myTestClass.cs我的TestClass.cs

        public class myTestClass {
            public myTestClass(){}
            
            public void getKey(){
                // Non-Controller class has access to AppData.Config w/o injection
                var key= AppData.Config.GetValue<string>("appSettings:key");
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有办法全局访问 appSettings.json ? - Is there a way to access appSettings.json globally? 在.net核心的单元测试中使用和注入appsettings.json - Using and injecting from appsettings.json in unit tests on .net core 如何从 ASP.NET Core 6 controller 中的 appsettings.json 访问值 - How to access a value from appsettings.json in ASP.NET Core 6 controller 访问控制器类中的appsettings.json值 - Access appsettings.json values in controller classes 如何在控制台应用程序 (.net Core) 中将数据写入 appsettings.json? - How to write data to appsettings.json in a console application (.net Core)? 如何从 .NET 核心中的 appsettings.json 读取部分值 - How to read section values from appsettings.json in .NET Core 如何在 .NET Core 的 appSettings.json 上配置 IdentiyServer 设置? - How to configure IdentiyServer settings on appSettings.json of .NET Core? 如何使用.Net core 5在任何Class中读取appsettings.json - How to read appsettings.json in any Class with .Net core 5 如何从 .net core 中的 appsettings.json 中提取列表 - How to extract a list from appsettings.json in .net core 如何控制appsettings.json部署基于.Net Core环境 - how to control the appsettings.json deployment based on environment in .Net Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM