Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core get connection string from appsettings.json

Tags:

I develop a simple web app and, in the future, I want to do it as multi-tenancy.

So I want to write the connection string straight into OnConfiguring method:

public class ApplicationContext : DbContext {     public DbSet<User> Users { get; set; }      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)     {         optionsBuilder.UseSqlServer("connection string from appsettings.json");         base.OnConfiguring(optionsBuilder);     } } 

Startup class:

public void ConfigureServices(IServiceCollection services) {     services.AddDbContext<ApplicationContext>();     services.AddMvc(); } 

How can I extract connection string from appsettings.json into ApplicationContext class?

I wouldn't like to create any constructors for ApplicationContext class.

like image 539
A. Gladkiy Avatar asked Oct 24 '16 12:10

A. Gladkiy


People also ask

How can I get the connection string from Appsettings json in .NET core?

Step1: Open Visual Studio 2017 and select here ASP.NET CORE 2.0 project template. Step2: Open Appsettting. json file and add following code snippet for adding connectionstring. Step4: Now in order to read the data of connection string in db class, write following code snippets.

How does json define connection string in Appsettings?

To define the connection strings in appsettings. json it is important to specify it in the right section of the JSON structure. Now we can read it in our code by calling the GetConnectionString method in the Microsoft. Extensions.

How do I get Connectionstring in .NET core?

In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings. json , an environment variable, the user secret store, or another configuration source. See the Configuration section of the ASP.NET Core documentation for more details.


2 Answers

Let's imagine that you have .NET Core application and your appsettings.json file looks like this:

{   "Logging": {     "IncludeScopes": false,     "LogLevel": {       "Default": "Debug",       "System": "Information",       "Microsoft": "Information"     }   },   "Production": {     "SqliteConnectionString": "Filename=./MyDatabase.sqlite"   } } 

You can get SqliteConnectionString value from Startup.cs like this:

public void ConfigureServices(IServiceCollection services) {     var connection = Configuration["Production:SqliteConnectionString"];      services.AddDbContext<MyContext>(options =>         options.UseSqlite(connection)     );     ....  } 

And then in your DBContext you should add constructor that accepts DbContextOptions:

public class MyContext : DbContext {     public MyContext (DbContextOptions<MyContext> options) : base(options)     { }      ... } 
like image 127
gos Avatar answered Oct 13 '22 13:10

gos


.NET Core 2.0

Add this class:

// Requires NuGet package Microsoft.Extensions.Configuration.Json  using Microsoft.Extensions.Configuration; using System.IO;  namespace RutarBackgroundServices.AppsettingsJson {     public static class AppSettingsJson     {         public static string ApplicationExeDirectory()         {             var location = System.Reflection.Assembly.GetExecutingAssembly().Location;             var appRoot = Path.GetDirectoryName(location);              return appRoot;         }          public static IConfigurationRoot GetAppSettings()         {             string applicationExeDirectory = ApplicationExeDirectory();              var builder = new ConfigurationBuilder()             .SetBasePath(applicationExeDirectory)             .AddJsonFile("appsettings.json");              return builder.Build();         }       } } 

Get the value for the key "MssqlConnectionString" from the "appsettings.json" file:

var appSettingsJson = AppSettingsJson.GetAppSettings(); var connectionString = appSettingsJson["MssqlConnectionString"]; 

Create the file "appsettings.json" in the root directory of your project:

{   "MssqlConnectionString": "Server=yourip; Database=yourdbname; User Id=yourusername; Password=yourpassword; Pooling=true;",   "Db2ConnectionString": "Database=yourdbname;UserID=yourusername;Password=yourpassword;Server=yourip:yourport",   "SomeOtherKey": "SomeOtherValue" } 
like image 36
Tadej Avatar answered Oct 13 '22 11:10

Tadej