Define your connection string(s) in appsettings.json
{
"connectionStrings": {
"appDbConnection": "..."
}
}
Read its value on Startup
If you follow the convention and define your connection string(s) under connectionStrings
, you can use the extension method GetConnectionString()
to read its value.
public class Startup
{
public IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// Since you said you're using Dapper, I guess you might want to
// inject IDbConnection?
services.AddTransient<IDbConnection>((sp) =>
new SqlConnection(this.Configuration.GetConnectionString("appDbConnection"))
);
// ...
}
}
Use IDbConnection within the repository?
public interface ISpecificationRepository
{
Specification GetById(int specificationId);
}
public SpecificationRepository : ISpecificationRepository
{
private readonly IDbConnection _dbConnection;
public SpecificationRepository(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}
public Specification GetById(int specificationId)
{
const string sql = @"SELECT * FROM [YOUR_TABLE]
WHERE Id = @specId;";
return _dbConnection
.QuerySingleOrDefault<Specification>(sql,
new { specId = specificationId });
}
}
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.jsonpublic class ConnectionStringConfig { public string AppDbConnection { get; set; } }
-
Register that configuration on Startup
public void ConfigureServices(IServiceCollection services) { // ... services.Configure<ConnectionStringConfig>( this.Configuration.GetSection("connectionStrings") ); // ... }
-
Receive the accessor in your POCO
public class YourPoco { private readonly ConnectionStringConfig _connectionStringConfig; public YourPoco(IOptions<ConnectionStringConfig> configAccessor) { _connectionStringConfig = configAccessor.Value; // Your connection string value is here: // _connectionStringConfig.AppDbConnection; } }
Notes:
- See my sample codes on how to read values from appsettings.json both on Core 1.x and 2.0.
- See how I setup if you have more than 1 connection string.