I have a asp net core web api app that I made using Repository pattern. When a request comes to my controller, I call one of my services dependency methods, then in that Service that was just called, I call another service, which is just my Repository layer. This class in the repository layer MyRepo.cs
relies on a DBContext.cs
class I made.
// Appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Database": {
"ConnectionString": connection string"
}
}
// Program.cs
// APPSETTIGS CONFIG
builder.services.Configure<DatabaseConfig>(
config.GetSection(DatabaseConfig.ConfigSectionName)); //Appsetting `Database` property
builder.services.AddScoped<IMyService, MyService>();
builder.services.AddScoped<IMyRepo, MyRepo>();
// MyService.cs
public class MyService: IMyService
{
private IMyRepo _myRepo;
public SurveyFormDataServices(IMyRepo myRepo)
{
_myRepo= myRepo;
}
public IEnumerable<MyTypes> GetTypes()
{
var types= _myRepo.GetTypes();
...
}
}
// MyRepo.cs
public class MyRepo: IMyRepo
{
private SqlConnection sqlConnection;
public IEnumerable<MyType> GetTypes()
{
using (sqlConnection = DBContext.GetConnection())
{
...
}
}
}
// DBContext.cs
public sealed class DBContext
{
private readonly DatabaseConfig _options;
private static string connectionString = string.Empty;
public DBContext(IOptions<DatabaseConfig> options)
{
_options = options.Value;
connectionString = _options.ConnectionString;
}
public static SqlConnection GetConnection()
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
}
As you can see in my DBContext.cs
class, the constructor has a parameter IOptions
from the injected AppSettings. I did the options pattern by also binding it to a class that represent the settings.
What my issue is, in the MyRepo.cs
, if I do this:
using (sqlConnection = DBContext.GetConnection())
The connectionString
property in my DBContext.cs
file will be empty, since I am guessing I did not instantiate with new DBProvider(IOptions)
. I want to avoid this and even if I do it like this, I get an error because I don’t know how to pass in IOptions
, and I rather not.
How can I call or use the DBContext.GetConnection()
function and ensure GetConnection()
will have the connectionString
value from the appsettings.json