I'm looking for the best practice way to store a connection string in appsettings.json in a .net Core 2 MVC app (like you do in web.config in MVC 5).
I want to use Dapper not EF (I found many EF examples).
Something like this:
{
"ConnectionStrings": {
"myDatabase": "Server=.;Database=myDatabase;Trusted_Connection=true;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
Surely there are many examples online? Nothing I can find that is for .net core 2.0.
Several things have changed between 1 and 2 and I want to ensure I'm using version 2 best practices.
I've found this - but it seems to be .net core 1: Visual Studio 2017 - MVC Core - Part 05 - Connection String from appsettings.json
This uses key value pair appsettings - not the connectionstrings: Read AppSettings in ASP.NET Core 2.0
Again it's unclear if this is .net Core 1 or 2: Net Core Connection String Dapper visual studio 2017
Just put like shown below in appsettings.json.
In Startup.cs fetch it as mentioned below:
Use dependency injection to inject configuration in controller like mentioned below:
Define your connection string(s) in
appsettings.json
Read its value on Startup
If you follow the convention and define your connection string(s) under
connectionStrings
, you can use the extension methodGetConnectionString()
to read its value.Use IDbConnection within the repository?
Just need the connection string in a POCO?
You might use the Options Pattern.
Define a class that exactly matches the
JSON
object structure in appsettings.jsonRegister that configuration on Startup
Receive the accessor in your POCO
Notes: