Skip to content

Configuring Connection Strings in .NET 6

Problem

With the transition to .NET 6, ASP.NET Core applications no longer use separate Startup and Program classes. This architectural change has left many developers wondering how to properly configure database connection strings and register their DbContext with the dependency injection container using the new minimal hosting model.

Solution

Overview of Changes in .NET 6

.NET 6 introduced the WebApplication and WebApplicationBuilder classes, which streamline application configuration by combining what was previously split between Startup.cs and Program.cs. The essential elements are:

  • WebApplication.CreateBuilder(args) replaces the traditional setup
  • builder.Configuration provides access to configuration values
  • builder.Services replaces the IServiceCollection from the Startup class

Step-by-Step Solution

1. Install Required NuGet Packages

First, ensure you have the necessary packages installed:

bash
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

2. Configure Connection String in appsettings.json

Add your connection string to the configuration file:

json
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=your_server;Database=your_database;User Id=your_user;Password=your_password;"
  }
}

3. Configure DbContext in Program.cs

Use the simplified builder pattern to register your DbContext:

cs
var builder = WebApplication.CreateBuilder(args);

// Register DbContext with SQL Server provider
builder.Services.AddDbContext<YourDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

var app = builder.Build();
// ... rest of application setup

4. Configure DbContext Class

Ensure your DbContext class is properly structured:

cs
public class YourDbContext : DbContext
{
    public YourDbContext(DbContextOptions<YourDbContext> options)
        : base(options)
    {
    }
    
    // DbSet properties
    public DbSet<YourEntity> YourEntities { get; set; }
}

Alternative Approaches

While you can manually build the configuration, this approach is more verbose and not typically necessary:

cs
var objBuilder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfiguration configuration = objBuilder.Build();

var connectionString = configuration.GetConnectionString("DefaultConnection");

WARNING

This manual approach is generally unnecessary in .NET 6 as the WebApplicationBuilder automatically handles configuration loading with the appropriate base path and file sources.

Accessing Connection String in Controllers

If you need to access the connection string directly in a controller:

cs
public class HomeController : Controller
{
    private readonly IConfiguration _configuration;
    
    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    
    public IActionResult Index()
    {
        var connectionString = _configuration.GetConnectionString("DefaultConnection");
        // Use connection string as needed
        return View();
    }
}

Best Practices

  1. Security: Never hardcode connection strings in your source code
  2. Environment-specific configuration: Use different appsettings.{Environment}.json files for development, staging, and production
  3. Secret Management: Use the Secret Manager tool for development or Azure Key Vault/AWS Secrets Manager for production to store sensitive connection information

Key Changes from Previous Versions

  • No separate Startup.cs class in the default template
  • WebApplicationBuilder provides centralized access to configuration and services
  • Configuration is automatically loaded from appsettings.json and environment variables
  • The builder.Configuration property replaces IConfiguration injection in the Startup constructor

Troubleshooting

Common Issues

  • Missing NuGet packages: Ensure you have both Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer installed
  • Incorrect connection string name: Verify the name in GetConnectionString() matches your appsettings.json
  • DbContext not configured: Make sure you're calling AddDbContext before building the application

The .NET 6 minimal hosting model provides a cleaner, more streamlined approach to application configuration while maintaining all the functionality of previous versions.