3

In my asp.net core service, I have this in the startup

services.AddDbContext<Mydb_Context>(
    options => options.UseSqlServer(Configuration["Settings:ConnString"]));

and to make it works, I created also this snippet:

public Mydb_Context(DbContextOptions<Mydb_Context> options) : base(options)
{
    //other stuff here
}

My problem now is: in "other stuff here" section, how can I read the options value and retrieve my connection string? Since there another dll and not the same project, I can't just read it again from the appsettings.json.

If I break my code during a debug session, I can see the connection string in the value inside this object, but I don't know how to get it properly. I see this value inside the "Extension" attribute of the options object.

So, how can I read the DbContextOptions value?

1 Answer 1

4

So, how can I read the DbContextOptions value?

You can (not publicly but using some EF Core internal infrastructure objects, in particular RelationalOptionsExtension class), but you don't need to.

To get the connection information, simply use context Database property and GetDbConnection method:

public Mydb_Context(DbContextOptions<Mydb_Context> options) : base(options)
{
    //other stuff here
    var connectionString = this.Database.GetDbConnection().ConnectionString;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.