Read application settings in asp net console application

I am trying to read appsetting on my console application, and also set the connection string to EntityFramework.

I did a lot of google, but did not find a single solution even in the Microsoft documentation.

Here are my questions.

  • How to set the connection string of EntityFramework ?, my object framework project is separate, for my MVC project I did this as shown below.
string connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<MyDBContext>(option =>option.UseSqlServer(connectionString, m => m.MigrationsAssembly("MyMVCDLL"))); services.Configure<AppSettings>(Configuration.GetSection("AppSettings")); 
  1. How to read the application?
  2. How to implement DI in a console application to get application settings?

Can someone help me with this.

+6
source share
1 answer

First, do not save sensitive data (username, password, API keys) in appsettings.json , as you may accidentally pass it to Verison Control and, therefore, the risk of leakage of your credentials. To do this, you need to use the User Secrets tool for development, for more details see the Secret user documentation .

Second, read the documentation at the tip of the Configuration.GetConnectionString("DefaultConnection"); method Configuration.GetConnectionString("DefaultConnection"); . It clearly states that `GetConnectionString -

Shortcut for GetSection ("ConnectionStrings") [name]

In doing so, your appsettings.json should look like this:

 { ..., "ConnectionStrings": { "DefaultConnection" : "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;" } } 

or when using user secrets:

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

Update

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

Required packages (depending on which one 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 for creating the configuration is exactly the same as in ASP.NET Core. Instead, in Startup.cs you do this 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) .AddUserSecrets() .AddEnvironmentVariables(); 
+7
source

Source: https://habr.com/ru/post/1011534/


All Articles