The TaskHub.Shared.Persistence.EntityFramework module provides a standard way to implement your data layer while inheriting powerful infrastructure features like automated auditing and Outbox pattern integration.
Inherit from ContextBase<TEntity> to create your service-specific DbContext.
using TaskHub.Shared.Persistence.EntityFramework.Context;
using TaskHub.Shared.Persistence.EntityFramework.Options;
namespace MyApp.Infrastructure.Persistence;
// TEntity is the primary entity managed by this context, or a marker class
public class MyDbContext(ContextOptions settings) : ContextBase<MyMainEntity>(settings)
{
public DbSet<OtherEntity> OtherEntities => Set<OtherEntity>();
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Additional configurations if not using IEntityTypeConfiguration<T>
}
}
Inherit from UnitOfWorkBase<TContext> to leverage the built-in domain event to Outbox message conversion.
using TaskHub.Shared.Persistence.EntityFramework.UnitOfWorks;
using TaskHub.Shared.Persistence.EntityFramework.Options;
using TaskHub.Shared.Persistence.Outbox.Factory;
namespace MyApp.Infrastructure.Persistence;
public class MyUnitOfWork(
MyDbContext db,
IOutboxMessageFactory factory,
PersistenceOptions options)
: UnitOfWorkBase<MyDbContext>(db, factory, options);
Configure the persistence section in appsettings.json.
"Persistence": {
"ConnectionString": "Host=localhost;Database=MyApp;Username=admin;Password=secret",
"Outbox": {
"IsEnabled": true,
"TableName": "OutboxMessages",
"BatchSize": 100
}
}
Register the context and unit of work using the AddAppDbContext extension.
using TaskHub.Shared.Persistence.EntityFramework.Bootstrap;
builder.Services.AddAppDbContext<MyDbContext>(builder.Configuration.GetSection("Persistence").Bind);
builder.Services.AddScoped<IUnitOfWork, MyUnitOfWork>();
The ContextBase automatically calls builder.ApplyConfigurationsFromAssembly(settings.Assembly). This means you can keep your entity configurations in separate files by implementing IEntityTypeConfiguration<T>.
The module supports EF Core Interceptors for:
CreatedAt or UpdatedAt fields on entities (if implemented).Database calls are automatically instrumented when using AddAppOpenTelemetry. This provides: