Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How force DbContexts to read from the connection string in the right appsettings

I have multiple DbContexts in my project
I am using .Net 6 and efCore 6. I am passing connection string to the contexts like this.

public partial class MyContext : DbContext
{    
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
    public MyContext() : base() { }
}

And in program.cs

services.AddDbContext<MyContext>(options =>
{
     options.UseSqlServer(Configuration.GetSection("MyConnrctionStr").Value);     
});

The problem is I should delegate the creation of my DbContext to a third party library that does not pass connection string to the context.
So I should handle setting the right connection string in my dbContext classes themselves. Also the config should come from corresponding environment settings i.e. development, production, debug, …
So that should be something like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


public partial class MyContext : DbContext
{    
    public MyContext(DbContextOptions<MyContext> options) : base(options) { }
    public MyContext() : base() { }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
        var string connectionStr= //Read ConnectionString From Correct appsettings.json file Regarding to Environment
            optionsBuilder.UseSqlServer(connectionStr);
        }
}

How can I achieve that?

>Solution :

You can have current environment name in the class and then read the appsetting.[currentenvironment].json with some code like this.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(getConnectionString());
    }
    private static string getConnectionString()
    {
        var environmentName =
          Environment.GetEnvironmentVariable(
              "ASPNETCORE_ENVIRONMENT");

        var config = new ConfigurationBuilder().AddJsonFile("appsettings" + (String.IsNullOrWhiteSpace(environmentName) ? "" : "." + environmentName) + ".json", false).Build();
        return config.GetConnectionString("DefaultConnection");
    }

This way you do not need to send any thing when injecting DBContext, etc. But the name of connection string would be hard codded inside DbContext

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading