Skip to content

WIP: Add Unit Of Work / Transaction support#21

Open
pdeffendol wants to merge 2 commits intomainfrom
unit-of-work
Open

WIP: Add Unit Of Work / Transaction support#21
pdeffendol wants to merge 2 commits intomainfrom
unit-of-work

Conversation

@pdeffendol
Copy link
Copy Markdown
Contributor

@pdeffendol pdeffendol commented Feb 4, 2024

Description

This PR adds an implementation of the Unit of Work pattern so that multiple repository operations can be wrapped into a transaction and either committed or rolled back together.

Yes, EF Core DbContext already acts as a Unit of Work pattern implementation. You're welcome to use EF directly in your application but you will likely have less control over how your entities are populated, which may make it difficult to follow DDD patterns such as Aggregate.

You can register the EF Core implementation with your dependency injection like this:

builder.Services.AddUnitOfWork();

then use it in your code by injecting into the consuming class:

public class MyService(IUnitOfWork uow, ...)
{
  public void DoStuff()
  {
    uow.BeginTransaction();
    // Do repository stuff here
    uow.Commit();
  }
}

What type of PR is this? (check all applicable)

  • 🍕 Feature
  • 🐛 Bug Fix
  • 📝 Documentation
  • 🎨 Style
  • 🧑‍💻 Code Refactor
  • 🔥 Performance Improvements
  • ✅ Tests
  • 🤖 Build/CI
  • 📦 Chore (Version bump, release, etc.)
  • ⏩ Revert

Related Tickets & Documents

none

Changes Made

See above

Quality Checklist

  • I have added or updated automated tests as needed.
  • I have reviewed the code changes myself.
  • I have used commit messages that adequately explain my changes.
  • I have removed any extra logging, debugging code, and commented out code.
  • I have updated any related documentation (if necessary).

Additional Notes

Open for discussion as to the name of the interface and class.

This allows wrapping repository operations in a transaction so that
they can be atomically committed to the database or rolled back
in case of error.
@pdeffendol
Copy link
Copy Markdown
Contributor Author

Seems like SQLite in-memory doesn't have normal transaction support, based on the failing "update and rollback" test.

@pdeffendol
Copy link
Copy Markdown
Contributor Author

I would prefer to keep this code out of the library, as it may promote some non-ideal practices, such as the modifying of multiple aggregates in a single transaction, which is frowned upon by DDD purists. Perhaps we should just document the mechanism and projects can implement it internally if desired.

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