Skip to main content

Generic Db Context Registration

tip

Includes registration for Audit.Net and Soft Deletes which are documented elsewhere

dotnet add package NodaTime
dotnet add package Audit.NET
dotnet add package Audit.EntityFramework.Core
dotnet add package EFCore.NamingConventions
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime
EntityFrameworkExtensions.cs
public static IServiceCollection AddCustomDbContext<DBCTX>(
this IServiceCollection services,
string connectionString)
where DBCTX : Microsoft.EntityFrameworkCore.DbContext
{
services.AddSingleton<SoftDeleteInterceptor>();
services.AddSingleton<AuditSaveChangesInterceptor>();

var dataSourceBuilder = new NpgsqlDataSourceBuilder(connectionString);
dataSourceBuilder.UseNodaTime();

var dataSource = dataSourceBuilder.Build();

services.AddDbContextPool<DBCTX>((provider, options) =>
{
options.UseNpgsql(dataSource, o =>
{
o.UseNodaTime();
})
.UseSnakeCaseNamingConvention();

options.AddInterceptors(
provider.GetRequiredService<SoftDeleteInterceptor>(),
provider.GetRequiredService<AuditSaveChangesInterceptor>()
);
});

return services;
}