Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

ASP.NET Core - Reading Config

$
0
0

It used to be so easy to read a configuration from anywhere and now it is rather a hassle.

I would like to do something like

public static class ConnectionString
{
    //
    //  Database Connection Strings
    //
    public static string DB1 => Configuration["ConnectionStrings:ConnectionString1"];
    public static string DB2 => Configuration["ConnectionStrings:ConnectionString2"];
    public static string DB3 => Configuration["ConnectionStrings:ConnectionString3"];
}

The problem is that I need to have a reference to an IConfiguration (in my example above Configuration) which I don't have access to as this is in a Data Access Layer project.

The very hacky approach I took was to add the following to the above code

public static IConfiguration Configuration { get { return ConfigurationManager.Configuration; } }

Create a separate project file that has only

using Microsoft.Extensions.Configuration;

namespace Config
{
    static public class ConfigurationManager
    {
        public static IConfiguration Configuration { get; set; }
    }
}

and then add it to the startup class

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            ConfigurationManager.Configuration = configuration;
        }

That way it is accessible from everywhere.

I know this is hacky but there has got to be a betterand easier way to get to this information.

How can something like this be implemented?

I should also add that I am migrating a legacy app and I don't have the luxury of rewriting everything to allow for DI.  I have 1000's of examples like this I am dealing with.

static public DataSet GetRecords(string cmdText)
{
    using (var conn = new SqlConnection(ConnectionString.DB1))
    {
        using (var cmd = new SqlCommand(cmdText, conn))
        {
            conn.Open();
            var ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            return ds;
        }
    }
}

Any help is greatly appreciated


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>