I have a .net core app. I write my connection string in appsettings.json file. But, now, I want to get that connection string for my context. How to do that?
In .net framework 4.6 I used this:
ConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;
I have appsettings.Development.json like this (*** could be any name):
"ConnectionStrings": {
"***": "Server=***;Database=****;Trusted_Connection=True;MultipleActiveResultSets=true;"
}
I added service:
services.AddTransient<MyContext>(provider =>
{
return new MyContext(configuration["ConnectionStrings:***"]);
});
and this is context constructor (ONLY THIS, not default ones because if I write a default one doesn't take my connection string from json file):
public MyContext(string connectionString)
: base(connectionString)
{
try
{
this.Database.Log = (s) => System.Diagnostics.Debug.Write(s);
}
catch (Exception e)
{
//CurrentLogger.Log.Error(e);
}
}
After that I've got this error after I run Enable-Migration command
The target context 'MyContext' is not constructible. Add a default constructor or provide an implementation of IDbContextFactory.
If somehow I could get connection string from json here:
all will be good. But I want to do that with a single line in .NET CORE if it would be possible, like in .net framework: with this:
ConfigurationManager.ConnectionStrings["ConnStrName"].ConnectionString;
.net framework 4.6

