Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

I have the following class in NET Core2.0 App.

// required when local database does not exist or was deleted public class ToDoContextFactory : IDesignTimeDbContextFactory<AppContext> {     public AppContext CreateDbContext(string[] args)     {         var builder = new DbContextOptionsBuilder<AppContext>();         builder.UseSqlServer("Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true");         return new AppContext(builder.Options);     } } 

This is required in Core 2.0 with migration when Database does not exist and has to be created when you run update-database.
Unable to create migrations after upgrading to ASP.NET Core 2.0

I would like not having ConnectionString in 2 places(here and in appsettings.json) but only in .json so I have tried to replace

"Server=localhost;Database=DbName;Trusted_Connection=True;MultipleActiveResultSets=true" 

with

ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString 

but it's not working, I'm getting null value.

UPDATE 1:
Just to note that adding explicitly .json is not necessery in Core 2 so the problem is not with the file.
https://andrewlock.net/exploring-program-and-startup-in-asp-net-core-2-preview1-2/

UPDATE 2:
Also I am already using Configuration for sending ConnectionString from .json to Context:

public class Startup {     public Startup(IConfiguration configuration)     {         Configuration = configuration;     }      public IConfiguration Configuration { get; }      public void ConfigureServices(IServiceCollection services)     {         services.AddDbContext<AppContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));     } } 

But I can not use this for ToDoContextFactory because it does not have Configuration, and ToDoContextFactory is used by migrations so the App is not running at all.

SOLUTION: Based on answer from @JRB I made it work like this:

public AppContext CreateDbContext(string[] args) {     string projectPath = AppDomain.CurrentDomain.BaseDirectory.Split(new String[] { @"bin\" }, StringSplitOptions.None)[0];     IConfigurationRoot configuration = new ConfigurationBuilder()         .SetBasePath(projectPath)         .AddJsonFile("appsettings.json")         .Build();     string connectionString = configuration.GetConnectionString("DefaultConnection");      var builder = new DbContextOptionsBuilder<AppContext>();     builder.UseSqlServer(connectionString);      return new AppContext(builder.Options); } 
like image 913
borisdj Avatar asked Aug 21 '17 12:08

borisdj


People also ask

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.

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

Adding the AppSettings.json file json file, right click on the Project in Solution Explorer. Then click Add, then New Item and then choose App Settings File option (shown below) and click Add button. Once the File is created, it will have a DefaultConnection, below that a new Connection String entry is added.


2 Answers

STEP 1: Include the following in OnConfiguring()

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)     {         IConfigurationRoot configuration = new ConfigurationBuilder()             .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)             .AddJsonFile("appsettings.json")             .Build();         optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));     } 

STEP 2: Create appsettings.json:

  {     "ConnectionStrings": {              "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"             }    } 

STEP 3: Hard copy appsettings.json to the correct directory

  Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory.    Use your debugger to find out which directory that is.         

Assumption: you have already included package Microsoft.Extensions.Configuration.Json (get it from Nuget) in your project.

like image 162
JRB Avatar answered Nov 15 '22 22:11

JRB


In ASPNET Core you do it in Startup.cs

public void ConfigureServices(IServiceCollection services) {     services.AddDbContext<BloggingContext>(options =>         options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase"))); } 

where your connection is defined in appsettings.json

{   "ConnectionStrings": {     "BloggingDatabase": "..."   }, } 

Example from MS docs

like image 23
Roman Gudkov Avatar answered Nov 16 '22 00:11

Roman Gudkov