Passing application's connection string down to a Repository Class Library in ASP.NET 5 using the IConfigurationRoot
on your Startup.cs file add the following method
public void ConfigureServices(IServiceCollection services) {
services.AddSingleton(_ => Configuration);
}
then update your BaseRepo class like this
public class BaseRepo {
private readonly IConfiguration config;
public BaseRepo(IConfiguration config) {
this.config = config;
}
public SqlConnection GetOpenConnection() {
string cs = config["Data:DefaultConnection:ConnectionString"];
SqlConnection connection = new SqlConnection(cs);
connection.Open();
return connection;
}
}
ASP.NET provides its own way of passing around configuration settings.
Suppose you have the this in your appSettings.json:
{
"Config": {
"Setting1": 1,
"Setting2": "SO"
}
}
Then you need a class like this:
public class MyConfiguration
{
public int Setting1 { get; set; }
public string Setting2 { get; set; }
}
This allows you to configure your service with this configuration by adding the following line
services.Configure<MyConfigurationDto>(Configuration.GetSection("Config"));
to ConfigureServices
.
You can then inject the configuration in constructors by doing the following:
public class SomeController : Controller
{
private readonly IOptions<MyConfiguration> config;
public ServiceLocatorController(IOptions<MyConfiguration> config)
{
this.config = config;
}
[HttpGet]
public IActionResult Get()
{
return new HttpOkObjectResult(config.Value);
}
}
This example is for controllers. But you can do the same with other layers of you application.
I have a constructor in my repository class that accepts the db connection string as a parameter. This works for me when I add my repository for injection. In ConfigureServies() of the startup.cs file add this:
services.AddScoped<IRepos>(c => new Repos(Configuration["DbConnections:ConnStr1"]));
IRepos.cs
is the interface, Repos.cs
is the class that implements it. And of course Configuration is just a reference to the built IConfigurationRoot
object.