Skip to content

fix(persistence): Fix Identity DbContext Interceptor Loop & Universal Auditing#1223

Open
cesarcastrocuba wants to merge 1 commit intofullstackhero:developfrom
cesarcastrocuba:fix/identity-dbcontext-interceptor-loop
Open

fix(persistence): Fix Identity DbContext Interceptor Loop & Universal Auditing#1223
cesarcastrocuba wants to merge 1 commit intofullstackhero:developfrom
cesarcastrocuba:fix/identity-dbcontext-interceptor-loop

Conversation

@cesarcastrocuba
Copy link

[Fix]: Fix Identity DbContext Interceptor Loop & Universal Auditing

Description

This PR addresses the StackOverflowException reported in Issue #15 by implementing a centralized audit interceptor in the Building Blocks. It includes a robust recursion guard to prevent infinite loops during the SaveChanges pipeline.

Key Changes

  • AuditableEntitySaveChangesInterceptor: Added to BuildingBlocks/Persistence. This interceptor automates:
    • Auditing: Automatically populates CreatedOnUtc, CreatedBy, LastModifiedOnUtc, and LastModifiedBy for entities implementing IAuditableEntity.
    • Soft Delete: Manages soft deletion for ISoftDeletable entities, transforming Delete operations into Update with the corresponding metadata.
    • Recursion Guard: Utilizes a [ThreadStatic] flag to detect nested SaveChanges calls, effectively preventing stack overflow errors.
  • Global Registration: Updated PersistenceExtensions.cs to register this and other interceptors (DomainEventsInterceptor) globally for any DbContext using the AddHeroDbContext extension.

Benefits

  • Robustness: Eliminates the technical risk of infinite loops within the Entity Framework pipeline.
  • Cleaner Code: Removes the need for manual assignments of audit metadata (creation/modification dates and users) in domain models/handlers.
  • System-wide Consistency: Ensures a uniform pattern for metadata and soft deletion across all modules.

Verification

  • Logic validated via unit tests covering insertion, modification, soft delete, and recursion scenarios.
  • dotnet build completed successfully (0 errors).
  • dotnet test verified for Generic.Tests (43 passing tests).

…ursion guard

- Implemented AuditableEntitySaveChangesInterceptor to handle IAuditableEntity and ISoftDeletable.
- Added a recursion guard using [ThreadStatic] bool _isSaving to prevent StackOverflowException.
- Registered the interceptor globally in PersistenceExtensions.
- Registered TimeProvider.System as a singleton service.
- Registered DomainEventsInterceptor in PersistenceExtensions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant