This sample demonstrates a Two-Phase Commit (2PC) style transaction using .NET 8 and Entity Framework Core. It simulates a bank transfer between two separate SQL Server instances running in Docker containers.
2PC-Demo/
├── src/
│ ├── Contexts/ # Database context classes
│ │ BankAContext.cs
│ │ BankBContext.cs
│ │
│ ├── Models/ # Entity models
│ │ Account.cs
│ │
│ ├── Data/ # Database initialization
│ │ DbInitializer.cs
│ │
│ ├── Services/ # Business logic
│ │ BankTransferService.cs
│ │
│ ├── Program.cs # Application entry point
│ ├── appsettings.json # Configuration
│ └── TwoPhaseCommitDemo.csproj
│
└── docker-compose.yml # Docker configuration
- Two-Phase Commit pattern implementation
- Automatic database initialization and seeding
- Simulated failure scenario for testing rollbacks
- Clean separation of concerns (services, data, models)
- Detailed console logging with Serilog
docker-compose up -dWait until both containers are healthy:
docker psSuccess scenario:
cd src
dotnet runFailure scenario (simulates error after first commit):
cd src
dotnet run --fail-
On startup:
- Creates both databases if they don't exist
- Seeds initial test accounts:
- BankA: Account1 with 1000
- BankB: Account2 with 500
-
During transfer:
- Attempts to transfer 100 from BankA to BankB
- Uses transaction coordination to ensure consistency
- Either both operations succeed or both rollback
-
In failure scenario:
- Simulates error after BankA update
- Demonstrates automatic rollback
- Ensures data consistency across both databases
- Uses SQL Server instances:
- BankA on port 1433
- BankB on port 1434
- Data is reset on each run for clean demo
- Uses TransactionScope for coordinating transactions
- Detailed logging shows each phase of the 2PC process
- Ensure Docker containers are running and healthy
- Check if ports 1433 and 1434 are available
- Verify SQL Server connection strings in appsettings.json
- Look at console logs for detailed error information