Search code examples
asp.net-coreconfigurationclass-library

How do I get a connection string in a .net core standard class library from the configuration file in a .net core 2.0 web app?


I have .net core standard class library which is essentially a DAL with several class methods that return collections and objects from a database. The connection string is in the appsettings.json file of the ASP.net 2 core web app. I also want to access this class library from a console app project where the configuration file with the connection string will be present in that console app project.

This was simple in .net prior to .net core. The DAL class library would just access the web.config from a web project and an app.config from a console application as it the library is referenced in both the web app and console apps. But it doesn't seem like this is at all possible.

I'm looking for the simple solution in .net core to get a connection string from web app or console app as the case may be.


Solution

  • It is very much possible to access "connection strings" or other configuration data easily in .Net core without much additional effort.

    Just that the configuration system has evolved (into something much better) & we have to make allowances for this as well (& follow recommended practices).

    In your case as you are accessing the connection string value in a standard library (intended to be reused), you should not make assumptions as how the configuration values will be "fed" to your class. What this means is you should not write code to read a connection string directly from a config file - instead rely on the dependency injection mechanism to provide you with the required configuration - regardless of how it has been made available to your app.

    One way to do this is to "require" an IConfiguration object to be injected into your class constructor & then use the GetValue method to retrieve the value for the appropriate key, like so:

    public class IndexModel : PageModel
    {
        public IndexModel(IConfiguration config)
        {
            _config = config;
        }
    
        public int NumberConfig { get; private set; }
    
        public void OnGet()
        {
            NumberConfig = _config.GetValue<int>("NumberKey", 99);
        }
    }
    

    In .net core, before the app is configured and started, a "host" is configured and launched. The host is responsible for app startup and lifetime management. Both the app and the host are configured using various "configuration providers". Host configuration key-value pairs become part of the app's global configuration.

    Configuration sources are read in the order that their configuration providers are specified at startup.

    .Net core supports various "providers". Read this article for complete information on this topic.