Home > Blockchain >  Use appsettings value in a different c# class in a different project
Use appsettings value in a different c# class in a different project

Time:05-05

I have the following appsettings.json in the core project:

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

and I have created a POCO:

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

This is my 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();
}

}

I want to access the values of the appsettings in the following class (in a different project):

public class OtherClass : SomeotherClass, SomeInterface { private string _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
}

I am fairly new to .net and any type of help will be appreciated. I also have added only details I thought would be relevant, please let me know if I need to add something else to shed details on something you may require.

CodePudding user response:

Common way to do this - register OtherClass in DI (based on ILogger<something> logger in ctor parameters I think you already do), add another ctor parameter for ABC, store it in a field and use the field in the method (remove corresponding parameter). For example:

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
    }

Read more:

  • Related