Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

You Don't need to Hard Code the Connection String #3

Closed
RehanSaeed opened this issue Apr 19, 2016 · 2 comments
Closed

You Don't need to Hard Code the Connection String #3

RehanSaeed opened this issue Apr 19, 2016 · 2 comments

Comments

@RehanSaeed
Copy link
Contributor

RehanSaeed commented Apr 19, 2016

You don't need to hard code the connection string in the DbContext. I am using the following code:

public MyApplicationDbContext()
    : base(JsonConvert.DeserializeObject<AppSettings>(
        File.ReadAllText(Path.Combine(Assembly.GetExecutingAssembly().Location, "appSettings.json")))
            .ConnectionStrings
            .MyApplication)
{
}

My appSettings.json looks like this:

{
    "ConnectionStrings": {
        "MyApplication": "[INSERT CONNECTION STRING HERE]"
    }
}

Works Great!

@mrahhal
Copy link
Owner

mrahhal commented Apr 19, 2016

That also works but be careful. Using this you're reading from a file (+ deserializing) every time DI decides to create an instance of your DbContext which is probably on every request and maybe more. VERY bad.

You can simply read that in your Startup and store the connection string in a static prop on your DbContext. Yeah this sounds a lot better.

@mrahhal
Copy link
Owner

mrahhal commented Apr 19, 2016

Ah, on second thoughts I see what you did. Calling the migrator won't call Startup. That's why I hard coded it in the first place. I guess we can make a default ctor like yours but write another one with the connection string as an argument that we will register with DI in order to avoid hard coding stuff and also avoid unnecessary performance hits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants