I checked some related questions, like this or this but they don't really seem to answer my question. I have a simple Client <=> Server application. For local development I want to store the connection string in Secrets Manager (secrets.json) outside the project.
When I try to inject the IConfiguration in a DB Context, it is empty in one of the projects - and when trying to read the connection string I get an error messsage:
System.ArgumentNullException: 'Value cannot be null. Arg_ParamName_Name'
The strange thing is that I have two projects that look very, very similar - not to say the same - regarding this functionality. One works just fine, the other one does not.
This I have in Program.cs. The GetConnectionString method returns the correct connection string:
ConfigurationManager configuration = builder.Configuration; // allows both to access and to set up the config
IWebHostEnvironment environment = builder.Environment;
var ConnectionString = configuration.GetConnectionString("OPS_DB");
builder.Services.AddDbContext<TestContext>(options => options.UseSqlServer(ConnectionString));
builder.Services.AddSingleton<IConfiguration>(configuration);
In my DB context I have this. Calling GetConnectionString returns NULL here.
public partial class TestContext : DbContext
{
IConfiguration configuration;
public TestContext()
{
}
public TestContext(DbContextOptions<TestContext> options, IConfiguration configuration)
: base(options)
{
this.configuration = configuration;
}
public virtual DbSet<DbScalingLevels> DbScalingLevels { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
String _connStr = this.configuration.GetConnectionString("OPS_DB"); // NULL !!
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(_connStr);
}
}
This is my secret.json:
{
"ConnectionStrings": {
"OPS_DB": "Data Source=some connection string"
}
}
As mentioned earlier, one project configured like this works just fine, another one does not. What is it I don't see here?
Put a (not) working example on GitHub.