using System.Text.Json; using Flensrocker.EventSourcing.Abstractions; using Flensrocker.EventSourcing.Abstractions.PersistentProjection; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace Flensrocker.EventSourcing.Persistence.EntityFrameworkCore; public static class EntityFrameworkCoreDomainEventStoreExtensions { extension(IServiceCollection services) { public IServiceCollection AddDomainEventStoreDbProvider() where TDbProvider : class, IDomainEventStoreDbProvider { services.AddScoped(); services.AddScoped(sp => sp.GetRequiredService()); return services; } public EntityFrameworkCoreDomainEventStoreBuilder AddDomainEventStore( Func configureOptions, Func configureDbOptions, Action configureDbContext ) where TDbProvider : class, IDomainEventStoreDbProvider { var storageOptions = configureOptions(); services.TryAddSingleton(storageOptions); services.AddDomainEventStoreDbProvider(); var contextOptions = configureDbOptions(); services.AddSingleton(contextOptions); services.AddPooledDbContextFactory( (serviceProvider, dbOptions) => { var rootConfiguration = serviceProvider.GetRequiredService(); var connectionString = rootConfiguration.GetConnectionString(storageOptions.ConnectionName); configureDbContext(connectionString, dbOptions); } ); return new EntityFrameworkCoreDomainEventStoreBuilder(services).ForDomainEvents(); } } public static DomainEvent ToDomainEvent(this MessageEntity entity, JsonSerializerOptions? jsonOptions) where TEventBase : class { return new DomainEvent { Metadata = new DomainEventMetadata { EventId = entity.Id, StreamType = entity.StreamType, StreamId = entity.StreamId, StreamVersion = entity.StreamVersion, TenantId = entity.TenantId, CreatedAt = entity.CreatedAt, CreatedByUserId = entity.CreatedByUserId, TraceId = entity.TraceId, SpanId = entity.SpanId, }, Payload = JsonSerializer.Deserialize(entity.PayloadJson, jsonOptions) is TEventBase p ? p : default!, }; } }