Commit c42fa9c1 authored by Almouhannad's avatar Almouhannad

Use option pattern for database context in program.cs

parent 12ac1d8a
namespace API.Options.Database;
public class DatabaseOptions
{
// Must match keys in appsettings.json
public string ConnectionString { get; set; } = string.Empty;
public int MaxRetryCount { get; set; }
public int CommandTimeout { get; set; }
public bool EnableDetailedErrors { get; set; }
}
using Microsoft.Extensions.Options;
namespace API.Options.Database;
public class DatabaseOptionsSetup : IConfigureOptions<DatabaseOptions>
{
private const string _cofigurationSectionName = "DatabaseOptions"; // From appsettings.json
#region Using ctor DI to access configuration
private readonly IConfiguration _configuration;
public DatabaseOptionsSetup(IConfiguration configuration)
{
_configuration = configuration;
}
#endregion
public void Configure(DatabaseOptions options)
{
var connectionString = _configuration.GetConnectionString("DefaultConnection");
options.ConnectionString = connectionString!; // Not null
// Get string values from section, and parsing them
_configuration.GetSection(_cofigurationSectionName).Bind(options);
}
}
using API.Options.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Persistence.Context;
var builder = WebApplication.CreateBuilder(args);
#region Add Database context
// First, get database options
builder.Services.ConfigureOptions<DatabaseOptionsSetup>();
builder.Services.AddDbContext<ClinicsDbContext>(
(serviceProvider, dbContectOptionsBuilder) =>
{
// Now, get options just like any other service
var databaseOptions = serviceProvider.GetService<IOptions<DatabaseOptions>>()!.Value;
dbContectOptionsBuilder.UseSqlServer(databaseOptions.ConnectionString, sqlServerAction =>
{
sqlServerAction.EnableRetryOnFailure(databaseOptions.MaxRetryCount);
sqlServerAction.CommandTimeout(databaseOptions.CommandTimeout);
});
// Be careful with this option, true only in development process!
dbContectOptionsBuilder.EnableDetailedErrors(databaseOptions.EnableDetailedErrors);
});
#endregion
// Add services to the container.
#region Link controllers with presentation layer
......
{
"ConnectionStrings": {
"DefaultConnection": "server=.\\;database=Clinics;Trusted_Connection=True; Encrypt=False;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"DatabaseOptions": {
"MaxRetryCount": 3,
"CommandTimeout": 30,
"EnableDetailedErrors": true
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment