EDIT: Passing down the configuration from an ASP.NET controller is not going to work if it is running in a console application.
Background:
- The DLL will be shipped with different applications, some console, some ASP.NET MVC and some WebAPI
- I'm building a .NET Core C# processing DLL which needs several configuration entries from appsettings.json.
- I'd like to make the DLL C# methods all static if possible for simplicity.
- An example configuration entry would be "SxProcFull" with values of true or false. There are about 10 configuration entries needed for the DLL
- The DLL is part of a much larger code base and is called multiple levels down from a web controller method or console app's main method
How can I get the configuration entry from inside the DLL?
Most of the examples on the web are for ASP.NET and oversimplify by putting the config entry code in the controller method with the configuration service passed into the controller method.
The .NET Core docs are long on what type of providers exist yet short on real-world examples.
Related links:
Understanding .net Core Dependency Injection in a console app
https://espressocoder.com/2018/12/03/build-a-console-app-in-net-core-like-a-pro/
https://blog.bitscry.com/2017/05/30/appsettings-json-in-net-core-console-app/
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-3.0&tabs=windows
And many more...
Edit: Moving the multi-app type item to top of background list.
ANSWER:
using System;
using System.IO;
using System.Reflection;
using Microsoft.Extensions.Configuration;
namespace AspNetCoreTestProject2
{
public static class MyConfiguration
{
private static IConfigurationRoot GetConfigRoot()
{
var assemblyLoc = Assembly.GetExecutingAssembly().Location;
var directoryPath = Path.GetDirectoryName(assemblyLoc);
var configFilePath = Path.Combine(directoryPath, "appsettings.json");
if (File.Exists(configFilePath) == false)
{
throw new InvalidOperationException("Config file not found");
}
IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile(configFilePath);
var configRoot = builder.Build();
return configRoot;
}
public static string ConfigGetConnectionStringByName(string connnectionStringName)
{
if (string.IsNullOrWhiteSpace(connnectionStringName))
{
throw new ArgumentException(nameof(connnectionStringName));
}
var root = GetConfigRoot();
var ret = root.GetConnectionString(connnectionStringName);
if (string.IsNullOrWhiteSpace(ret))
{
throw new InvalidOperationException("Config value cannot be empty");
}
return ret;
}
public static string ConfigEntryGet(string configEntryName)
{
if (string.IsNullOrWhiteSpace(configEntryName))
{
throw new ArgumentException(nameof(configEntryName));
}
var root = GetConfigRoot();
var ret = root[configEntryName];
if (string.IsNullOrWhiteSpace(ret))
{
throw new InvalidOperationException("Config value cannot be empty");
}
return ret;
}
}
}