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

9
  • 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? Commented Jan 27, 2016 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. Commented Jan 27, 2016 at 20:44
  • @Tim it's just a separate DLL, like you said. Commented Jan 27, 2016 at 21:12
  • @mason what namespace would be used for that since ConfigurationManager doesn't work anymore? Commented Jan 27, 2016 at 21:20
  • ASP.NET 5 is dead : hanselman.com/blog/… Sorry for your loss Commented Jan 27, 2016 at 21:25

3 Answers 3

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;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
-1
        //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 Comment

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.
-2

//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;
            }

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.