Having a Different ConnectionString in ASP.NET Core for each Operating System

I love .NET Core. It really has been a great framework to develop web applications and Web APIs. I especially enjoy developing ASP.NET Core Web API solutions on my MBP using JetBrains Rider just to have a different experience besides Windows. The second best feature of .NET Core in my opinion (number one is dependency injection) is the ability to develop and execute ASP.NET Core solutions on Linux and macOS operating systems.

I recently wrote a blog post for work on how to create and access from macOS a Microsoft SQL Server database inside a Docker container. That is a great way to run an MSSQL database on a non-Windows OS. What about the configuration inside our ASP.NET Core projects? How can we connect to a local or remote SQL Server database or maybe from a Docker container? Let’s look at how to do that!

It is quite simple. We will be using the following namespace. There are no additional NuGet packages to install.

using System.Runtime.InteropServices;

In our example, we will set two ConnectionStrings for our project. One for Windows running a local Developer edition of SQL Server 2017. The other will be for SQL Server 2017 that is running on Linux inside Docker.

“ConnectionStrings”: {
“ChinookDbWindows”: “Server=.;Database=Chinook;Trusted_Connection=True;”,
“ChinookDbDocker”: “Server=localhost,1433;Database=Chinook;User=sa;Password=Passw0rd;Trusted_Connection=False;”

We will finally have a check to see at runtime what operating system the ASP.NET Core application is currently running on. We will use the RuntimeInformation class inside System.Runtime.InteropServices and the IsOSPlatform() method. Below is the sample code from my ChinookASPNETCoreAPINTier demo on GitHub.

string connection = String.Empty;

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
connection = configuration.GetConnectionString(“ChinookDbWindows”) ??
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
connection = configuration.GetConnectionString(“ChinookDbDocker”) ??

services.AddDbContextPool(options => options.UseSqlServer(connection));

I hope this gives you some additional information to move your .NET Core development to other non-Windows platforms. Cheers!


Finally the ASP.NET 5 Web API Blog Series!!