Read appsettings in asp net core console application c# console-application entity-framework-6


I'm trying to read the appsetting on my console application as well as to set he EntityFramework connection string.

I did a lot of google but did not found any single solution not even on Microsoft's documentation.

Here is the my questions.

  1. How to set the EntityFramework connection string?, my entity framework project is separate, for my MVC project I did this as below code.
string connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<MyDBContext>(option =>option.UseSqlServer(connectionString, m => m.MigrationsAssembly("MyMVCDLL")));
  1. How to read the appsetting?
  2. How to implement the DI in console applciation to get the appsettings?

Can someone help me with this.

10/22/2016 4:07:27 AM

Popular Answer

First, don't save sensitive data (login, password, API keys) in appsettings.json, as you can accidentally commit it to Verison Control and hence risk your credentials leaking. For this you have to use User Secrets tool for development, see the User Secret documentation for details.

Second, read the tooltip documentation of Configuration.GetConnectionString("DefaultConnection"); method. It clearly states that `GetConnectionString is a

Shorthand for GetSection(“ConnectionStrings”)[name]

That being said, your appsettings.json has to look like this:

        "DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;"

or when using user secrets:

dotnet user-secrets set ConnectionStrings:DefaultConnection Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;


Using it in the console application is exactly the same. The configuration package isn't ASP.NET Core specific and can be used on its own.

The required packages are (depending on which of them you want to use

"Microsoft.Extensions.Configuration": "1.0.0", "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0", "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0", "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0",

And the code to build the configuration is exactly the same as in ASP.NET Core. Just instead of doing it in Startup.cs you do it in the Main method:

var builder = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    // You can't use environment specific configuration files like this
    // becuase IHostingEnvironment is an ASP.NET Core specific interface
    //.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
10/21/2016 9:54:56 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow