I have an ASP.NET 5 MVC Web Application and in Startup.cs I see that the public property
IConfigurationRoot Configuration
is being set to
There is already an extension method you can use to get connection strings specifically from aspsettings.json.
Define your connection strings in appsettings.json like this:
{
"ConnectionStrings": {
"Local": "Data source=.\\SQLExpress;Initial Catalog=.......",
"Test:": "Data source=your-server;......"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
In your public void ConfigureServices(IServiceCollection services)
method inside your Startup.cs
, you can get the connection string like this:
var connectionString = this.Configuration.GetConnectionString("Local");
GetConnectionString
extension is from Microsoft.Extensions.Configuration
.UPDATE
I didn't want to go into details at first because the question here had already been marked as answered. But I guess I can show my 2 cents here.
If you do need the whole IConfigurationRoot
object injected into Controllers, @Chrono showed the right way.
If you don't need the whole object, you should just get the connection string, pass it into the DbContext inside the ConfigureServices()
call, and inject the DbContext
into Controllers. @Prashant Lakhlani showed it correctly.
I am just saying, in @Prashant Lakhlani post, you can use GetConnectionString
extension instead to clean up the code a little bit.