3

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;
    }
}
}
stak
  • 129
  • 1
  • 10
  • The configuration entries are all simple key,value pairs with no complex structure. – stak Oct 30 '19 at 17:40
  • 1
    Have a look at this [answer](https://stackoverflow.com/a/55019290) – Matt.G Oct 30 '19 at 18:17
  • Thanks Matt G. I've added a working solution based on the StackOverflow question you linked to. – stak Oct 30 '19 at 19:10
  • Production code would do more validation and exception handling. I'd also add a MyConfig C# wrapper class with methods for individual entries which would validate the entries so that a config entry which has a "true" or "false" value would accept "true", "false", "True", "False", "TRUE", ... – stak Oct 30 '19 at 19:13
  • That would avoid the fail of user edited config files for desktop applications. – stak Oct 30 '19 at 19:16

2 Answers2

0

I don't know why you copy the JSON in the folder with the Dlls and use this JSON. On Visual Studio you can select the JSON and set the property "copy into output path". If you do it like this you can use IConfiguration.

The class you get from the Initialization-Method in your Controller Class. Eg.:

public ApiController(IConfiguration configuration)
{
   Configuration = configuration;
}
private IConfiguration Configuration;

On other C# Appliactionyou can use this Nuget So read the JSON File with the StreamReader.

StreamReader sw = new StreamReader("myjason.json");
string json = sw.ReadToEnd();

Then use the JObject

JObject obj = JObject.Parse(json); 
string mainpath = (string)obj["paths"]["mainpath"];

Hope it helps.

BierDav

BierDav
  • 1,219
  • 1
  • 10
  • 27
  • BierDav, it's not only an ASP.NET Core application. The DLL is called from application types other than ASP.NET. The DLL would be copied into the calling application's exe directory which would also contain the appsettings json file. – stak Oct 30 '19 at 18:10
  • I've written `On other C# Appliaction you can use this Nuget So read the JSON File with the StreamReader.`. What's the matter. In the other Application-Types you read the File with the StreamReader (look at code part 2) and Parse it into a JObject (look at code part 3). You can use this also in ever Net. Core Application. Note to installl the Nuget and import this `using Newtonsoft.Json;`. – BierDav Feb 20 '20 at 11:50
0
    private readonly IConfiguration _config;

    public YourController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Testing()
    {
      string getKey = _config["Token:Key"]
    }

   If you have this sample json
   "Token": {
   "Key": "ktF2YqrBlhfdg444"
   }
OIbuoye
  • 289
  • 4
  • 7