TaskHub.Shared

Entity Framework Usage

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.

1. Implement Your DbContext

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>
    }
}

2. Implement Your Unit of Work

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);

3. Configuration & Registration

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>();

Key Features

Automated Configuration

The ContextBase automatically calls builder.ApplyConfigurationsFromAssembly(settings.Assembly). This means you can keep your entity configurations in separate files by implementing IEntityTypeConfiguration<T>.

Interceptors

The module supports EF Core Interceptors for:

Telemetry

Database calls are automatically instrumented when using AddAppOpenTelemetry. This provides: