Passing application's connection string down to a Repository Class Library in ASP.NET 5 using the IConfigurationRoot

后端 未结 7 1755
情话喂你
情话喂你 2020-12-08 19:51

I have an ASP.NET 5 MVC Web Application and in Startup.cs I see that the public property

IConfigurationRoot Configuration 

is being set to

相关标签:
7条回答
  • 2020-12-08 20:52

    There is already an extension method you can use to get connection strings specifically from aspsettings.json.

    1. Define your connection strings in appsettings.json like this:

       {
           "ConnectionStrings": {
               "Local": "Data source=.\\SQLExpress;Initial Catalog=.......",
               "Test:": "Data source=your-server;......"
           },
           "Logging": {
               "IncludeScopes": false,
               "LogLevel": {
                   "Default": "Debug",
                   "System": "Information",
                   "Microsoft": "Information"
               }
           }
      }
      
    2. In your public void ConfigureServices(IServiceCollection services) method inside your Startup.cs, you can get the connection string like this:

      var connectionString = this.Configuration.GetConnectionString("Local");
      
    3. The GetConnectionString extension is from Microsoft.Extensions.Configuration.
    4. Enjoy :)

    UPDATE

    I didn't want to go into details at first because the question here had already been marked as answered. But I guess I can show my 2 cents here.

    If you do need the whole IConfigurationRoot object injected into Controllers, @Chrono showed the right way.

    If you don't need the whole object, you should just get the connection string, pass it into the DbContext inside the ConfigureServices() call, and inject the DbContext into Controllers. @Prashant Lakhlani showed it correctly.

    I am just saying, in @Prashant Lakhlani post, you can use GetConnectionString extension instead to clean up the code a little bit.

    0 讨论(0)
提交回复
热议问题