I just started to build an API with net core 2.1.
I added my connection string in appsettings.json and I want to access it.
appsettings.json
"MySettings": {
"connectionString": "Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Subscription;Data Source=Test-Pc",
"Email": "abc@domain.com",
"SMTPPort": "5605"
}
First I added the configuration manager in startup.cs so that I can inject in other classes
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MyConfig>(Configuration.GetSection("appsettings"));
}
I have a class in which I initialize my SQLConnection, but I need to inject the appsettings so that I read the connection string.
ConnectionManager.cs
public class CustomSqlConnection : IDisposable
{
private SqlConnection sqlConn;
private readonly IOptions<MyConfig> _myConfig;
public CustomSqlConnection(IOptions<MyConfig> _Config = null)
{
_myConfig = _Config;
string connectionString = _myConfig.Value.connectionString;
if (string.IsNullOrEmpty(connectionString))
{
throw new Exception(string.Format("Connection string was not found in config file"));
}
this.sqlConn = new SqlConnection(connectionString);
}
}
However I want to call from another class.
CustomSqlConnection connection = new CustomSqlConnection()
However, IOptions<MyConfig> _Config
is showing me null.
What is the best practice to initialize a class that injects IOptions or any other interface.