在不同项目的不同 c# class 中使用 appsettings 值

Use appsettings value in a different c# class in a different project

我在核心项目中有以下appsettings.json:

  "ABC": {
    "Url": "someurl",
    "Id": "as",
    "sec": "bc",
    "Username": "un",
    "Password": "pw",
  }

并且我创建了一个 POCO:

public class ABC
{
    public string Username { get; set; }
    public string Password { get; set; }
}

这是我的 program.cs class:

public class Program
{   
    public IConfiguration Configuration { get; }

    public static void Main(string[] args)
    {
        var logger = LogManager.GetCurrentClassLogger();
            
        try
        {
            CreateHostBuilder(args).Build().Run();
        }
        catch (OperationCanceledException oex)
        {
            logger.Error(oex, "Error during shutdown");
            Environment.ExitCode = 3;
        }
            
    }
    public void ConfigureServices(IServiceCollection services)
    {
        // Adds services required for using options.
        services.AddOptions();
        services.AddSingleton<ABC>();
        // Registers the following lambda used to configure options.
        services.Configure<ABC>(Configuration.GetSection("ABC"));

        //register other services
        services.AddSingleton<ABC>();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) 
                var config = hostContext.Configuration;

                // load ABC into an object
                var ABC = config.GetSection("ABC").Get<ABC>();
                ABC.AppSection = "ABC";
                services.AddSingleton(ABC);

                services.AddHostedService<Service>()
                .Configure<EventLogSettings>(config =>
                {
                    config.LogName = "Aname";
                    config.SourceName = "Asource";
                });
            })
            .ConfigureLogging((options) =>
            {
                options.AddFilter<EventLogLoggerProvider>(level => level >= Microsoft.Extensions.Logging.LogLevel.Information);
                options.AddNLog("some.log");
            })
            .UseWindowsService();
}

}

我想访问以下 class(在不同的项目中)中的应用程序设置值:

public class 其他类:SomeotherClass,SomeInterface { 私有字符串 _Id;

public OtherClass(ILogger<something> logger, IZXC ZXC)
    : base(logger, ZXC)
{
}


public void DoRunDotNetPython(CancellationToken token, command zxc, List<NameValuePair> asd)
{
    some code 
     //access the values here
}

我是 .net 的新手,我们将不胜感激任何类型的帮助。我也只添加了我认为相关的详细信息,如果我需要添加其他内容以详细说明您可能需要的内容,请告诉我。

常用方法 - 在 DI 中注册 OtherClass(基于我认为你已经在 ctor 参数中的 ILogger<something> logger),为 ABC 添加另一个 ctor 参数,存储它在一个字段中并在方法中使用该字段(删除相应的参数)。例如:

public class OtherClass : SomeotherClass, SomeInterface
{
    private string _Id;
    private readonly ABC ABC;

    public OtherClass(ILogger<something> logger, IZXC ZXC, IOptions<ABC> abc)
        : base(logger, ZXC)
    {
        ABC = abc.Value;
    }

    public void DoRunDotNetPython(CancellationToken token, Command myCommand, List<NameValuePair> agentSettings)
    {
        // use ABC here
    }

阅读更多: