AppConfig and .NET5 database connections

Peder Thörnström 26 Reputation points
2021-08-06T02:57:10.953+00:00

Hi everyone,
I do development with C# and done so using .NET4.

Best practice, I've been told, and for many reasons is to have your connection string in AppConfig. Comming over to .NET5 AppConfig doesn't even exists. So, where should I keep the connection string now?

Would appreciate your help - just a link to some documentation will do.

Many thanks.

Developer technologies | .NET | .NET Runtime
Developer technologies | C#
0 comments No comments
{count} vote

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-08-06T09:27:23.95+00:00

    As @Timon Yang-MSFT indicated you can still use an App.config file but the favored way under .NET Core is to read connection strings and other settings in a file named appsettings.json.

    If you were using ASP.NET Core appsettings.json is easy to implement for reading connection strings while those writing desktop applications require to write code.

    I created a simple GitHub repository as a starter for getting a connection string from appsettings.json where in this case there are three connection strings, one for development, one for test and one for production. If you have only one environment then as coded set the development connection.

    Example appsettings.json

    {  
      "ConnectionStrings": {  
        "DevelopmentConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=NorthWind2020;Integrated Security=True",  
        "ProductionConnection": "Data Source=ProductionServer;Initial Catalog=NorthWind2020;Integrated Security=True",  
        "TestConnection": "Data Source=TestServer;Initial Catalog=NorthWind2020;Integrated Security=True",  
        "Environment": 2  
      }  
    }  
    

    Example usage to read from a SQL-Server database

    using System.Data.SqlClient;  
    using SqlServerConnectionLibrary;  
      
    namespace AppSettingsCoreUnitTestProject.Classes  
    {  
        public class SqlOperations  
        {  
            public static string ConnectionString = "";  
      
            public static CustomerRelation GetCustomers()  
            {  
      
                InitializeConnection();  
                  
                CustomerRelation customer = new();  
      
                var selectStatement = "TODO";  
      
                using var cn = new SqlConnection() { ConnectionString = ConnectionString };  
                using var cmd = new SqlCommand() { Connection = cn, CommandText = selectStatement };  
      
                cn.Open();  
      
                var reader = cmd.ExecuteReader();  
      
                if (reader.HasRows)  
                {  
                    reader.Read();  
                    customer.CustomerIdentifier = reader.GetInt32(0);  
                    customer.CompanyName = reader.GetString(1);  
                    customer.City = reader.GetString(2);  
                    customer.PostalCode = reader.GetString(3);  
                    customer.ContactId = reader.GetInt32(4);  
                    customer.CountryIdentifier = reader.GetInt32(5);  
                    customer.Country = reader.GetString(6);  
                    customer.Phone = reader.GetString(7);  
                    customer.PhoneTypeIdentifier = reader.GetInt32(8);  
                    customer.ContactPhoneNumber = reader.GetString(9);  
                    customer.ModifiedDate = reader.GetDateTime(10);  
                    customer.FirstName = reader.GetString(11);  
                    customer.LastName = reader.GetString(12);  
                }  
      
                return customer;  
      
            }  
      
            private static void InitializeConnection()  
            {  
                if (!string.IsNullOrWhiteSpace(ConnectionString)) return;  
                Helper.Initializer();  
                ConnectionString = Helper.ConnectionString;  
            }  
        }  
    }  
    

    We can have other properties stored in appsettings.json e.g.

    {  
      "GeneralSettings": {  
        "LogExceptions": true,  
        "DatabaseSettings": {  
          "DatabaseServer": ".\\SQLEXPRESS",  
          "Catalog": "School",  
          "IntegratedSecurity": true,  
          "UsingLogging": true  
        },  
        "EmailSettings": {  
          "Host": "smtp.gmail.com",  
          "Port": 587,  
          "EnableSsl": true,  
          "DefaultCredentials": false,  
          "PickupDirectoryLocation": "MailDrop"  
        }  
      }  
    }  
    

    Not included but wanted to show other configuration possibilities

    121135-config1.png

    And last note, with not much effort we can programmatically change settings in the appsettings.json file. With that, if you can a setting while the app is running the change will be recognized.

    GitHub solution

    121156-solution.png


1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,606 Reputation points
    2021-08-06T07:02:43.393+00:00

    One way is to add a nuget package: System.Configuration.ConfigurationManager, and then manually add an App.config file, just like using it in the .Net Framework:

                string connectionString = ConfigurationManager.ConnectionStrings["Model1"].ConnectionString;  
                Console.WriteLine(connectionString);  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.