Skip to content

Refactor DbContext Domain Event Dispatching Responsibility #944

Open
@mokarchi

Description

@mokarchi

Summary

The current implementation of AppDbContext mixes Persistence and Domain Event Dispatching responsibilities by directly injecting an IDomainEventDispatcher and handling event dispatch after SaveChangesAsync.
This violates clean architecture principles.

Problem Details

  • Single Responsibility Violation: DbContext should only handle persistence logic. Event dispatching should be separated.
  • Performance Impact: Dispatching domain events synchronously after save might impact request latency.
  • Hidden Dependency: Accepting a nullable dispatcher (IDomainEventDispatcher?) hides required dependencies and introduces a service locator anti-pattern.

Suggested Solution

  • Remove IDomainEventDispatcher from DbContext constructor.
  • Introduce an SaveChangesInterceptor to handle domain event dispatching after SaveChanges or SaveChangesAsync.
  • Register the interceptor via Dependency Injection and attach it inside DbContextOptionsBuilder.
  • Ensure clean separation of concerns between Persistence Layer and Domain Layer.

Benefits

  • Better adherence to Clean Architecture principles.
  • Better maintainability and scalability for future improvements.
  • Improved request performance and reduced transaction coupling.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions