1

With the new ASP.NET 5 doing away with web.config, and thus the ConfigurationManagement namespace, I was trying to figure out how to read the connection string from my data access layer project in my MVC application.

Researching this issue, everything I've found says to just read the config value from the project.json configuration file in the Startup.cs file like this:

var configuration = new Configuration();
configuration.AddJsonFile("config.json");
configuration.AddEnvironmentVariables();

//////

var connString = configuration.Get("Data:DefaultConnection:ConnectionString");

But I don't want my web project having anything to do with the data access. So, how does my data access layer project retrieve the connection string in this setup?

Update: Here's my startup.cs file and the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    // Add Identity services to the services container.
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    // Add MVC services to the services container.
    services.AddMvc();

    // Register application services.
    services.Configure<ApplicationOptions>(options =>
    {
        options.ConnectionString = "Data:DefaultConnection:ConnectionString";
    });
}

And here's my DataAccessLayer project, and my RepoBase.cs class

public class RepoBase
{
    //private readonly string _connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
    //private readonly string _connectionString = Environment.GetEnvironmentVariable("ConnectionString");
    private readonly string _connectionString;

    public RepoBase(IOptions<ApplicationOptions> appOptions)
    {
        this._connectionString = appOptions.ConnectionString;

        // or just read directly from System.Configuration.Get("");
    }

    protected SqlConnection GetConnection()
    {
        var conn = new SqlConnection(_connectionString);
        conn.OpenAsync();

        return conn;
    }
}

This is where I'm drawing a blank as to how to retrieve my ApplicationOptions object in my DAL project, or just read the connectionstring value that is set in the Startup.cs

configuration.AddEnvironmentVariables()

method call.

Update 2: Oh, is this what I need to use from my Data Access Layer to access the environment variables: https://github.com/aspnet/configuration/blob/master/src/Microsoft.Extensions.Configuration.EnvironmentVariables/EnvironmentVariablesConfigurationProvider.cs

ganders
  • 7,285
  • 17
  • 66
  • 114
  • 3
    If the DA layer is a DLL, it should be able to read the project.json file of the consuming application. If it's its own application, it would have its own project.json file. Unless there's a part of the equation I'm missing? – Tim Jan 27 '16 at 20:35
  • 2
    There's nothing wrong with having your web project retrieve the connection string and pass it to the data layer. Or the web project can pass its entire configuration to the data layer and then the data layer can pick and choose what it wants out of the configuration. – mason Jan 27 '16 at 20:44
  • @Tim it's just a separate DLL, like you said. – ganders Jan 27 '16 at 21:12
  • @mason what namespace would be used for that since ConfigurationManager doesn't work anymore? – ganders Jan 27 '16 at 21:20
  • ASP.NET 5 is dead : http://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx Sorry for your loss – Mark Schultheiss Jan 27 '16 at 21:25
  • ASP.NET CORE 1.0 has arisen from the ashes. It must be a phoenix or something – Mark Schultheiss Jan 27 '16 at 21:42
  • @Ganders What namespace is `Configuration` in your code? Seems like you should be able to pass that `configuration` variable. – mason Jan 27 '16 at 21:52
  • @mason I updated my question... – ganders Jan 28 '16 at 13:25
  • There is nothing preventing you from either passing a connection string directly, passing an instance of the `Configuration` class and having your data access layer pull out what it needs, or having your web project convert from the `Configuration` class to the `IOptions` in your current constructor. Just pick one. Also, your `GetConnection` method is a disaster waiting to happen. You shouldn't just open a connection, because you need to make absolutely sure it will get closed, even in the event of an error. Use `try/catch/finally` or a `using` block. – mason Jan 28 '16 at 13:50

3 Answers3

2

This is a duplicate of this

On your ConfigureServices method add your configuration object as a singleton.

public void ConfigureServices(IServiceCollection services) {
    services.AddSingleton(_ => configuration);
}

then update your BaseRepo class like this

public class BaseRepo {
    private readonly IConfigurationRoot config;

    public BaseRepo(IConfigurationRoot config) {
        this.config = config;
    }

    public static SqlConnection GetOpenConnection() {
        var cs = config.Get<string>("Data:DefaultConnection:ConnectionString");
        var connection = new SqlConnection(cs);
        connection.Open();
        return connection;
    }
}
Community
  • 1
  • 1
Manos Pasgiannis
  • 1,693
  • 1
  • 18
  • 30
  • This still has one issue. The data access classes (BaseRepo) are in a separate DLL, so presumably could be used in other applications. Because BaseRepo reads the ConnectionString directly from IConfigurationRoot (appsettings.json) then that forces all clients to use the same name (key) for that ConnectionString. Would it be better for ConnectionString and other values from appsettings.json to be input to BaseRepo constructor? How to do that with the .NET 5 Dependency Injection? Then another app could have the connection string called something else in it's appsettings.json file. – iceman Jan 26 '22 at 16:54
0
        //inside this mehtod connection string is used
        public DataTable GetDataTable(string cmdText)
        {
            DataTable dt = new DataTable();           
            var constr = OnConfiguring(); //this method is called to get connection string

            using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmdText, con);
                da.SelectCommand.CommandType = CommandType.StoredProcedure;
                da.Fill(dt);
            }
            return dt;
        }
    }
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 06 '21 at 16:41
-1

//this method is used to return connection string

            protected  string OnConfiguring() 
            {

                var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).
                    AddJsonFile("appsettings.json", optional: true,
                    reloadOnChange: true);
appsettings.json file            
                string dbConnection = builder.Build().GetSection("ConnectionStrings").GetSection("DevConnections").Value;
                return dbConnection;
            }
  • This is the best suitable way to access connection string , if you are planning to use ADO.net or 3 tier layer code in dot net core. – Ramesh Chandan Oct 30 '21 at 07:41
  • 1
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Oct 30 '21 at 08:37