├── .gitattributes ├── .gitignore ├── Core ├── OutboxExample.Application │ ├── Features │ │ └── Commands │ │ │ └── CreateOrder │ │ │ ├── CreateOrderCommandHandler.cs │ │ │ ├── CreateOrderCommandRequest.cs │ │ │ └── CreateOrderCommandResponse.cs │ ├── OutboxExample.Application.csproj │ ├── Repositories │ │ ├── IOrderInboxRepository.cs │ │ ├── IOrderOutboxRepository.cs │ │ ├── IOrderRepository.cs │ │ └── IRepository.cs │ └── ServiceRegistrations.cs └── OutboxExample.Domain │ ├── Entities │ ├── Order.cs │ ├── OrderInbox.cs │ └── OrderOutbox.cs │ └── OutboxExample.Domain.csproj ├── Infrastructure └── OutboxExample.Persistence │ ├── Context │ └── OutboxExampleDbContext.cs │ ├── EntityConfigurations │ ├── OrderConfiguration.cs │ ├── OrderInboxConfiguration.cs │ └── OrderOutboxConfiguration.cs │ ├── Migrations │ ├── 20220724032225_mig_1.Designer.cs │ ├── 20220724032225_mig_1.cs │ ├── 20220724144051_mig_2.Designer.cs │ ├── 20220724144051_mig_2.cs │ └── OutboxExampleDbContextModelSnapshot.cs │ ├── OutboxExample.Persistence.csproj │ ├── Repositories │ ├── OrderInboxRepository.cs │ ├── OrderOutboxRepository.cs │ ├── OrderRepository.cs │ └── Repository.cs │ └── ServiceRegistrations.cs ├── OutboxExample.Shared ├── Events │ ├── Base │ │ └── IEvent.cs │ └── OrderCreatedEvent.cs └── OutboxExample.Shared.csproj ├── OutboxExample.sln ├── Presentation ├── OutboxExample.Order.API │ ├── Controllers │ │ └── OrdersController.cs │ ├── OutboxExample.Order.API.csproj │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── appsettings.Development.json │ └── appsettings.json └── OutboxExample.Stock.API │ ├── Consumers │ └── OrderCreatedEventConsumer.cs │ ├── OutboxExample.Stock.API.csproj │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── appsettings.Development.json │ └── appsettings.json ├── TransactionLogService ├── OutboxExample.TransactionLog.Service │ ├── OutboxExample.TransactionLog.Service.csproj │ └── Program.cs ├── docker-compose-sqlserver.yaml └── register-sqlserver.json └── Worker └── OutboxExample.ProcessOutboxJob.Service ├── Contexts └── OrderSingletonDatabase.cs ├── Jobs └── OrderOutboxPublishJob.cs ├── OutboxExample.ProcessOutboxJob.Service.csproj ├── Program.cs ├── Properties └── launchSettings.json ├── appsettings.Development.json └── appsettings.json /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Features/Commands/CreateOrder/CreateOrderCommandHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using OutboxExample.Application.Repositories; 3 | using OutboxExample.Domain.Entities; 4 | using OutboxExample.Shared.Events; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | using System.Text; 9 | using System.Text.Json; 10 | using System.Threading.Tasks; 11 | 12 | namespace OutboxExample.Application.Features.Commands.CreateOrder 13 | { 14 | public class CreateOrderCommandHandler : IRequestHandler 15 | { 16 | readonly IOrderRepository _orderRepository; 17 | readonly IOrderOutboxRepository _orderOutboxRepository; 18 | 19 | public CreateOrderCommandHandler(IOrderRepository orderRepository, IOrderOutboxRepository orderOutboxRepository) 20 | { 21 | _orderRepository = orderRepository; 22 | _orderOutboxRepository = orderOutboxRepository; 23 | } 24 | 25 | public async Task Handle(CreateOrderCommandRequest request, CancellationToken cancellationToken) 26 | { 27 | Order order = new() { Description = request.Description }; 28 | await _orderRepository.AddAsync(order); 29 | 30 | OrderOutbox orderOutbox = new() 31 | { 32 | OccuredOn = DateTime.UtcNow, 33 | ProcessedDate = null, 34 | Payload = JsonSerializer.Serialize(order), 35 | Type = nameof(OrderCreatedEvent), 36 | IdempotentToken = Guid.NewGuid() 37 | }; 38 | await _orderOutboxRepository.AddAsync(orderOutbox); 39 | await _orderOutboxRepository.SaveChangesAsync(); 40 | return new(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Features/Commands/CreateOrder/CreateOrderCommandRequest.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace OutboxExample.Application.Features.Commands.CreateOrder 9 | { 10 | public class CreateOrderCommandRequest : IRequest 11 | { 12 | public int Quantity { get; set; } 13 | public string Description { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Features/Commands/CreateOrder/CreateOrderCommandResponse.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace OutboxExample.Application.Features.Commands.CreateOrder 8 | { 9 | public class CreateOrderCommandResponse 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/OutboxExample.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Repositories/IOrderInboxRepository.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Domain.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace OutboxExample.Application.Repositories 9 | { 10 | public interface IOrderInboxRepository : IRepository 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Repositories/IOrderOutboxRepository.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Domain.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace OutboxExample.Application.Repositories 9 | { 10 | public interface IOrderOutboxRepository : IRepository 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Repositories/IOrderRepository.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Domain.Entities; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace OutboxExample.Application.Repositories 9 | { 10 | public interface IOrderRepository : IRepository 11 | { 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/Repositories/IRepository.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Linq.Expressions; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace OutboxExample.Application.Repositories 9 | { 10 | public interface IRepository 11 | { 12 | IQueryable GetAll(); 13 | IQueryable GetWhere(Expression> method); 14 | Task AddAsync(T model); 15 | Task SaveChangesAsync(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Core/OutboxExample.Application/ServiceRegistrations.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace OutboxExample.Application 10 | { 11 | public static class ServiceRegistrations 12 | { 13 | public static void AddApplicationServices(this IServiceCollection services) 14 | { 15 | services.AddMediatR(typeof(ServiceRegistrations)); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Core/OutboxExample.Domain/Entities/Order.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace OutboxExample.Domain.Entities 8 | { 9 | public class Order 10 | { 11 | public Guid Id { get; set; } 12 | public int Quantity { get; set; } 13 | public string Description { get; set; } 14 | //public ICollection Products { get; set; } ... Example 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Core/OutboxExample.Domain/Entities/OrderInbox.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace OutboxExample.Domain.Entities 8 | { 9 | public class OrderInbox 10 | { 11 | public Guid OrderId { get; set; } 12 | public int Quantity { get; set; } 13 | public string Description { get; set; } 14 | public bool Processed { get; set; } 15 | public Guid IdempotentToken { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Core/OutboxExample.Domain/Entities/OrderOutbox.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace OutboxExample.Domain.Entities 8 | { 9 | public class OrderOutbox 10 | { 11 | public OrderOutbox() 12 | { 13 | } 14 | public DateTime OccuredOn { get; set; } 15 | public DateTime? ProcessedDate { get; set; } 16 | public string @Type { get; set; } 17 | public string Payload { get; set; } 18 | public Guid IdempotentToken { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Core/OutboxExample.Domain/OutboxExample.Domain.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Context/OutboxExampleDbContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using OutboxExample.Domain.Entities; 3 | using OutboxExample.Persistence.EntityConfigurations; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace OutboxExample.Persistence.Context 11 | { 12 | public class OutboxExampleDbContext : DbContext 13 | { 14 | public OutboxExampleDbContext(DbContextOptions options) : base(options) 15 | { 16 | } 17 | public DbSet Orders { get; set; } 18 | public DbSet OrderOutboxes { get; set; } 19 | public DbSet OrderInboxes { get; set; } 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | modelBuilder.ApplyConfiguration(new OrderConfiguration()); 23 | modelBuilder.ApplyConfiguration(new OrderOutboxConfiguration()); 24 | modelBuilder.ApplyConfiguration(new OrderInboxConfiguration()); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/EntityConfigurations/OrderConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | using OutboxExample.Domain.Entities; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace OutboxExample.Persistence.EntityConfigurations 11 | { 12 | public class OrderConfiguration : IEntityTypeConfiguration 13 | { 14 | public void Configure(EntityTypeBuilder builder) 15 | { 16 | builder.HasKey(p => p.Id); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/EntityConfigurations/OrderInboxConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | using OutboxExample.Domain.Entities; 4 | 5 | namespace OutboxExample.Persistence.EntityConfigurations 6 | { 7 | public class OrderInboxConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasKey(p => p.IdempotentToken); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/EntityConfigurations/OrderOutboxConfiguration.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 3 | using OutboxExample.Domain.Entities; 4 | 5 | namespace OutboxExample.Persistence.EntityConfigurations 6 | { 7 | public class OrderOutboxConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasKey(p => p.IdempotentToken); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Migrations/20220724032225_mig_1.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using OutboxExample.Persistence.Context; 9 | 10 | #nullable disable 11 | 12 | namespace OutboxExample.Persistence.Migrations 13 | { 14 | [DbContext(typeof(OutboxExampleDbContext))] 15 | [Migration("20220724032225_mig_1")] 16 | partial class mig_1 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.7") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("OutboxExample.Domain.Entities.Order", b => 28 | { 29 | b.Property("Id") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("uniqueidentifier"); 32 | 33 | b.Property("Description") 34 | .IsRequired() 35 | .HasColumnType("nvarchar(max)"); 36 | 37 | b.Property("Quantity") 38 | .HasColumnType("int"); 39 | 40 | b.HasKey("Id"); 41 | 42 | b.ToTable("Orders"); 43 | }); 44 | 45 | modelBuilder.Entity("OutboxExample.Domain.Entities.OrderOutbox", b => 46 | { 47 | b.Property("IdempotentToken") 48 | .ValueGeneratedOnAdd() 49 | .HasColumnType("uniqueidentifier"); 50 | 51 | b.Property("OccuredOn") 52 | .HasColumnType("datetime2"); 53 | 54 | b.Property("Payload") 55 | .IsRequired() 56 | .HasColumnType("nvarchar(max)"); 57 | 58 | b.Property("ProcessedDate") 59 | .HasColumnType("datetime2"); 60 | 61 | b.Property("Type") 62 | .IsRequired() 63 | .HasColumnType("nvarchar(max)"); 64 | 65 | b.HasKey("IdempotentToken"); 66 | 67 | b.ToTable("OrderOutboxes"); 68 | }); 69 | #pragma warning restore 612, 618 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Migrations/20220724032225_mig_1.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace OutboxExample.Persistence.Migrations 7 | { 8 | public partial class mig_1 : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "OrderOutboxes", 14 | columns: table => new 15 | { 16 | IdempotentToken = table.Column(type: "uniqueidentifier", nullable: false), 17 | OccuredOn = table.Column(type: "datetime2", nullable: false), 18 | ProcessedDate = table.Column(type: "datetime2", nullable: true), 19 | Type = table.Column(type: "nvarchar(max)", nullable: false), 20 | Payload = table.Column(type: "nvarchar(max)", nullable: false) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_OrderOutboxes", x => x.IdempotentToken); 25 | }); 26 | 27 | migrationBuilder.CreateTable( 28 | name: "Orders", 29 | columns: table => new 30 | { 31 | Id = table.Column(type: "uniqueidentifier", nullable: false), 32 | Quantity = table.Column(type: "int", nullable: false), 33 | Description = table.Column(type: "nvarchar(max)", nullable: false) 34 | }, 35 | constraints: table => 36 | { 37 | table.PrimaryKey("PK_Orders", x => x.Id); 38 | }); 39 | } 40 | 41 | protected override void Down(MigrationBuilder migrationBuilder) 42 | { 43 | migrationBuilder.DropTable( 44 | name: "OrderOutboxes"); 45 | 46 | migrationBuilder.DropTable( 47 | name: "Orders"); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Migrations/20220724144051_mig_2.Designer.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Migrations; 7 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 8 | using OutboxExample.Persistence.Context; 9 | 10 | #nullable disable 11 | 12 | namespace OutboxExample.Persistence.Migrations 13 | { 14 | [DbContext(typeof(OutboxExampleDbContext))] 15 | [Migration("20220724144051_mig_2")] 16 | partial class mig_2 17 | { 18 | protected override void BuildTargetModel(ModelBuilder modelBuilder) 19 | { 20 | #pragma warning disable 612, 618 21 | modelBuilder 22 | .HasAnnotation("ProductVersion", "6.0.7") 23 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 24 | 25 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 26 | 27 | modelBuilder.Entity("OutboxExample.Domain.Entities.Order", b => 28 | { 29 | b.Property("Id") 30 | .ValueGeneratedOnAdd() 31 | .HasColumnType("uniqueidentifier"); 32 | 33 | b.Property("Description") 34 | .IsRequired() 35 | .HasColumnType("nvarchar(max)"); 36 | 37 | b.Property("Quantity") 38 | .HasColumnType("int"); 39 | 40 | b.HasKey("Id"); 41 | 42 | b.ToTable("Orders"); 43 | }); 44 | 45 | modelBuilder.Entity("OutboxExample.Domain.Entities.OrderInbox", b => 46 | { 47 | b.Property("IdempotentToken") 48 | .ValueGeneratedOnAdd() 49 | .HasColumnType("uniqueidentifier"); 50 | 51 | b.Property("Description") 52 | .IsRequired() 53 | .HasColumnType("nvarchar(max)"); 54 | 55 | b.Property("OrderId") 56 | .HasColumnType("uniqueidentifier"); 57 | 58 | b.Property("Processed") 59 | .HasColumnType("bit"); 60 | 61 | b.Property("Quantity") 62 | .HasColumnType("int"); 63 | 64 | b.HasKey("IdempotentToken"); 65 | 66 | b.ToTable("OrderInboxes"); 67 | }); 68 | 69 | modelBuilder.Entity("OutboxExample.Domain.Entities.OrderOutbox", b => 70 | { 71 | b.Property("IdempotentToken") 72 | .ValueGeneratedOnAdd() 73 | .HasColumnType("uniqueidentifier"); 74 | 75 | b.Property("OccuredOn") 76 | .HasColumnType("datetime2"); 77 | 78 | b.Property("Payload") 79 | .IsRequired() 80 | .HasColumnType("nvarchar(max)"); 81 | 82 | b.Property("ProcessedDate") 83 | .HasColumnType("datetime2"); 84 | 85 | b.Property("Type") 86 | .IsRequired() 87 | .HasColumnType("nvarchar(max)"); 88 | 89 | b.HasKey("IdempotentToken"); 90 | 91 | b.ToTable("OrderOutboxes"); 92 | }); 93 | #pragma warning restore 612, 618 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Migrations/20220724144051_mig_2.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.EntityFrameworkCore.Migrations; 3 | 4 | #nullable disable 5 | 6 | namespace OutboxExample.Persistence.Migrations 7 | { 8 | public partial class mig_2 : Migration 9 | { 10 | protected override void Up(MigrationBuilder migrationBuilder) 11 | { 12 | migrationBuilder.CreateTable( 13 | name: "OrderInboxes", 14 | columns: table => new 15 | { 16 | IdempotentToken = table.Column(type: "uniqueidentifier", nullable: false), 17 | OrderId = table.Column(type: "uniqueidentifier", nullable: false), 18 | Quantity = table.Column(type: "int", nullable: false), 19 | Description = table.Column(type: "nvarchar(max)", nullable: false), 20 | Processed = table.Column(type: "bit", nullable: false) 21 | }, 22 | constraints: table => 23 | { 24 | table.PrimaryKey("PK_OrderInboxes", x => x.IdempotentToken); 25 | }); 26 | } 27 | 28 | protected override void Down(MigrationBuilder migrationBuilder) 29 | { 30 | migrationBuilder.DropTable( 31 | name: "OrderInboxes"); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Migrations/OutboxExampleDbContextModelSnapshot.cs: -------------------------------------------------------------------------------- 1 | // 2 | using System; 3 | using Microsoft.EntityFrameworkCore; 4 | using Microsoft.EntityFrameworkCore.Infrastructure; 5 | using Microsoft.EntityFrameworkCore.Metadata; 6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion; 7 | using OutboxExample.Persistence.Context; 8 | 9 | #nullable disable 10 | 11 | namespace OutboxExample.Persistence.Migrations 12 | { 13 | [DbContext(typeof(OutboxExampleDbContext))] 14 | partial class OutboxExampleDbContextModelSnapshot : ModelSnapshot 15 | { 16 | protected override void BuildModel(ModelBuilder modelBuilder) 17 | { 18 | #pragma warning disable 612, 618 19 | modelBuilder 20 | .HasAnnotation("ProductVersion", "6.0.7") 21 | .HasAnnotation("Relational:MaxIdentifierLength", 128); 22 | 23 | SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); 24 | 25 | modelBuilder.Entity("OutboxExample.Domain.Entities.Order", b => 26 | { 27 | b.Property("Id") 28 | .ValueGeneratedOnAdd() 29 | .HasColumnType("uniqueidentifier"); 30 | 31 | b.Property("Description") 32 | .IsRequired() 33 | .HasColumnType("nvarchar(max)"); 34 | 35 | b.Property("Quantity") 36 | .HasColumnType("int"); 37 | 38 | b.HasKey("Id"); 39 | 40 | b.ToTable("Orders"); 41 | }); 42 | 43 | modelBuilder.Entity("OutboxExample.Domain.Entities.OrderInbox", b => 44 | { 45 | b.Property("IdempotentToken") 46 | .ValueGeneratedOnAdd() 47 | .HasColumnType("uniqueidentifier"); 48 | 49 | b.Property("Description") 50 | .IsRequired() 51 | .HasColumnType("nvarchar(max)"); 52 | 53 | b.Property("OrderId") 54 | .HasColumnType("uniqueidentifier"); 55 | 56 | b.Property("Processed") 57 | .HasColumnType("bit"); 58 | 59 | b.Property("Quantity") 60 | .HasColumnType("int"); 61 | 62 | b.HasKey("IdempotentToken"); 63 | 64 | b.ToTable("OrderInboxes"); 65 | }); 66 | 67 | modelBuilder.Entity("OutboxExample.Domain.Entities.OrderOutbox", b => 68 | { 69 | b.Property("IdempotentToken") 70 | .ValueGeneratedOnAdd() 71 | .HasColumnType("uniqueidentifier"); 72 | 73 | b.Property("OccuredOn") 74 | .HasColumnType("datetime2"); 75 | 76 | b.Property("Payload") 77 | .IsRequired() 78 | .HasColumnType("nvarchar(max)"); 79 | 80 | b.Property("ProcessedDate") 81 | .HasColumnType("datetime2"); 82 | 83 | b.Property("Type") 84 | .IsRequired() 85 | .HasColumnType("nvarchar(max)"); 86 | 87 | b.HasKey("IdempotentToken"); 88 | 89 | b.ToTable("OrderOutboxes"); 90 | }); 91 | #pragma warning restore 612, 618 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/OutboxExample.Persistence.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | all 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Repositories/OrderInboxRepository.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Application.Repositories; 2 | using OutboxExample.Domain.Entities; 3 | using OutboxExample.Persistence.Context; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace OutboxExample.Persistence.Repositories 11 | { 12 | public class OrderInboxRepository : Repository, IOrderInboxRepository 13 | { 14 | public OrderInboxRepository(OutboxExampleDbContext context) : base(context) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Repositories/OrderOutboxRepository.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Application.Repositories; 2 | using OutboxExample.Domain.Entities; 3 | using OutboxExample.Persistence.Context; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace OutboxExample.Persistence.Repositories 11 | { 12 | public class OrderOutboxRepository : Repository, IOrderOutboxRepository 13 | { 14 | public OrderOutboxRepository(OutboxExampleDbContext context) : base(context) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Repositories/OrderRepository.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Application.Repositories; 2 | using OutboxExample.Domain.Entities; 3 | using OutboxExample.Persistence.Context; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace OutboxExample.Persistence.Repositories 11 | { 12 | public class OrderRepository : Repository, IOrderRepository 13 | { 14 | public OrderRepository(OutboxExampleDbContext context) : base(context) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/Repositories/Repository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using OutboxExample.Application.Repositories; 3 | using OutboxExample.Persistence.Context; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace OutboxExample.Persistence.Repositories 12 | { 13 | public class Repository : IRepository where T : class 14 | { 15 | readonly OutboxExampleDbContext _context; 16 | public Repository(OutboxExampleDbContext context) 17 | { 18 | this._context = context; 19 | } 20 | 21 | public DbSet Table { get => _context.Set(); } 22 | 23 | public async Task AddAsync(T model) 24 | => await Table.AddAsync(model); 25 | 26 | public IQueryable GetAll() 27 | => Table; 28 | 29 | public IQueryable GetWhere(Expression> method) 30 | => Table.Where(method); 31 | 32 | public async Task SaveChangesAsync() 33 | => await _context.SaveChangesAsync(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Infrastructure/OutboxExample.Persistence/ServiceRegistrations.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using OutboxExample.Application.Repositories; 4 | using OutboxExample.Persistence.Context; 5 | using OutboxExample.Persistence.Repositories; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace OutboxExample.Persistence 13 | { 14 | public static class ServiceRegistrations 15 | { 16 | public static void AddPersistenceServices(this IServiceCollection services) 17 | { 18 | services.AddDbContext(options => options.UseSqlServer("Server=localhost, 1433;Database=OutboxExampleDB;User ID=SA;Password=1q2w3e4r+!;")); 19 | 20 | services.AddScoped(); 21 | services.AddScoped(); 22 | services.AddScoped(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OutboxExample.Shared/Events/Base/IEvent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace OutboxExample.Shared.Events.Base 8 | { 9 | public interface IEvent 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /OutboxExample.Shared/Events/OrderCreatedEvent.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Shared.Events.Base; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace OutboxExample.Shared.Events 9 | { 10 | public class OrderCreatedEvent : IEvent 11 | { 12 | public Guid OrderId { get; set; } 13 | public int Quantity { get; set; } 14 | public string Description { get; set; } 15 | public Guid IdempotentToken { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /OutboxExample.Shared/OutboxExample.Shared.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /OutboxExample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.2.32505.173 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{E2ADF2EC-B313-4382-8451-9E9FDCB3455A}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Infrastructure", "Infrastructure", "{8B99E80A-EFEC-438F-A912-D70635638512}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Presentation", "Presentation", "{B5AE0988-6E25-434B-894A-06C6ED968EFF}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.Domain", "Core\OutboxExample.Domain\OutboxExample.Domain.csproj", "{A1D68043-A52C-4A5A-8928-5F942B1A8E43}" 13 | EndProject 14 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.Application", "Core\OutboxExample.Application\OutboxExample.Application.csproj", "{626C7E3A-C019-4DB9-9A39-69B690C36448}" 15 | EndProject 16 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.Persistence", "Infrastructure\OutboxExample.Persistence\OutboxExample.Persistence.csproj", "{9BA6CEE6-4D38-4FF2-9EE7-1C83F9A922B0}" 17 | EndProject 18 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.Order.API", "Presentation\OutboxExample.Order.API\OutboxExample.Order.API.csproj", "{3C624D85-4672-4C08-8018-685BA0F22C37}" 19 | EndProject 20 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.Shared", "OutboxExample.Shared\OutboxExample.Shared.csproj", "{41B0C496-2D2C-4811-8838-7F27965D60B0}" 21 | EndProject 22 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Worker", "Worker", "{36A9A63E-D3B2-46D1-B5B5-657937B75B13}" 23 | EndProject 24 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.ProcessOutboxJob.Service", "Worker\OutboxExample.ProcessOutboxJob.Service\OutboxExample.ProcessOutboxJob.Service.csproj", "{86ED44E3-33C5-4A74-8E94-82B0AC7CCEF4}" 25 | EndProject 26 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "TransactionLogService", "TransactionLogService", "{04105232-0103-4DE7-9707-578CCEB9D585}" 27 | ProjectSection(SolutionItems) = preProject 28 | TransactionLogService\docker-compose-sqlserver.yaml = TransactionLogService\docker-compose-sqlserver.yaml 29 | TransactionLogService\register-sqlserver.json = TransactionLogService\register-sqlserver.json 30 | EndProjectSection 31 | EndProject 32 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.TransactionLog.Service", "TransactionLogService\OutboxExample.TransactionLog.Service\OutboxExample.TransactionLog.Service.csproj", "{E25E94A6-E6A2-4459-8653-1BF2B826A32C}" 33 | EndProject 34 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutboxExample.Stock.API", "Presentation\OutboxExample.Stock.API\OutboxExample.Stock.API.csproj", "{D61F6785-F7E5-4B1C-9B88-20111FC6D339}" 35 | EndProject 36 | Global 37 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 38 | Debug|Any CPU = Debug|Any CPU 39 | Release|Any CPU = Release|Any CPU 40 | EndGlobalSection 41 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 42 | {A1D68043-A52C-4A5A-8928-5F942B1A8E43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {A1D68043-A52C-4A5A-8928-5F942B1A8E43}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {A1D68043-A52C-4A5A-8928-5F942B1A8E43}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {A1D68043-A52C-4A5A-8928-5F942B1A8E43}.Release|Any CPU.Build.0 = Release|Any CPU 46 | {626C7E3A-C019-4DB9-9A39-69B690C36448}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 47 | {626C7E3A-C019-4DB9-9A39-69B690C36448}.Debug|Any CPU.Build.0 = Debug|Any CPU 48 | {626C7E3A-C019-4DB9-9A39-69B690C36448}.Release|Any CPU.ActiveCfg = Release|Any CPU 49 | {626C7E3A-C019-4DB9-9A39-69B690C36448}.Release|Any CPU.Build.0 = Release|Any CPU 50 | {9BA6CEE6-4D38-4FF2-9EE7-1C83F9A922B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 51 | {9BA6CEE6-4D38-4FF2-9EE7-1C83F9A922B0}.Debug|Any CPU.Build.0 = Debug|Any CPU 52 | {9BA6CEE6-4D38-4FF2-9EE7-1C83F9A922B0}.Release|Any CPU.ActiveCfg = Release|Any CPU 53 | {9BA6CEE6-4D38-4FF2-9EE7-1C83F9A922B0}.Release|Any CPU.Build.0 = Release|Any CPU 54 | {3C624D85-4672-4C08-8018-685BA0F22C37}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 55 | {3C624D85-4672-4C08-8018-685BA0F22C37}.Debug|Any CPU.Build.0 = Debug|Any CPU 56 | {3C624D85-4672-4C08-8018-685BA0F22C37}.Release|Any CPU.ActiveCfg = Release|Any CPU 57 | {3C624D85-4672-4C08-8018-685BA0F22C37}.Release|Any CPU.Build.0 = Release|Any CPU 58 | {41B0C496-2D2C-4811-8838-7F27965D60B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 59 | {41B0C496-2D2C-4811-8838-7F27965D60B0}.Debug|Any CPU.Build.0 = Debug|Any CPU 60 | {41B0C496-2D2C-4811-8838-7F27965D60B0}.Release|Any CPU.ActiveCfg = Release|Any CPU 61 | {41B0C496-2D2C-4811-8838-7F27965D60B0}.Release|Any CPU.Build.0 = Release|Any CPU 62 | {86ED44E3-33C5-4A74-8E94-82B0AC7CCEF4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 63 | {86ED44E3-33C5-4A74-8E94-82B0AC7CCEF4}.Debug|Any CPU.Build.0 = Debug|Any CPU 64 | {86ED44E3-33C5-4A74-8E94-82B0AC7CCEF4}.Release|Any CPU.ActiveCfg = Release|Any CPU 65 | {86ED44E3-33C5-4A74-8E94-82B0AC7CCEF4}.Release|Any CPU.Build.0 = Release|Any CPU 66 | {E25E94A6-E6A2-4459-8653-1BF2B826A32C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 67 | {E25E94A6-E6A2-4459-8653-1BF2B826A32C}.Debug|Any CPU.Build.0 = Debug|Any CPU 68 | {E25E94A6-E6A2-4459-8653-1BF2B826A32C}.Release|Any CPU.ActiveCfg = Release|Any CPU 69 | {E25E94A6-E6A2-4459-8653-1BF2B826A32C}.Release|Any CPU.Build.0 = Release|Any CPU 70 | {D61F6785-F7E5-4B1C-9B88-20111FC6D339}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 71 | {D61F6785-F7E5-4B1C-9B88-20111FC6D339}.Debug|Any CPU.Build.0 = Debug|Any CPU 72 | {D61F6785-F7E5-4B1C-9B88-20111FC6D339}.Release|Any CPU.ActiveCfg = Release|Any CPU 73 | {D61F6785-F7E5-4B1C-9B88-20111FC6D339}.Release|Any CPU.Build.0 = Release|Any CPU 74 | EndGlobalSection 75 | GlobalSection(SolutionProperties) = preSolution 76 | HideSolutionNode = FALSE 77 | EndGlobalSection 78 | GlobalSection(NestedProjects) = preSolution 79 | {A1D68043-A52C-4A5A-8928-5F942B1A8E43} = {E2ADF2EC-B313-4382-8451-9E9FDCB3455A} 80 | {626C7E3A-C019-4DB9-9A39-69B690C36448} = {E2ADF2EC-B313-4382-8451-9E9FDCB3455A} 81 | {9BA6CEE6-4D38-4FF2-9EE7-1C83F9A922B0} = {8B99E80A-EFEC-438F-A912-D70635638512} 82 | {3C624D85-4672-4C08-8018-685BA0F22C37} = {B5AE0988-6E25-434B-894A-06C6ED968EFF} 83 | {86ED44E3-33C5-4A74-8E94-82B0AC7CCEF4} = {36A9A63E-D3B2-46D1-B5B5-657937B75B13} 84 | {E25E94A6-E6A2-4459-8653-1BF2B826A32C} = {04105232-0103-4DE7-9707-578CCEB9D585} 85 | {D61F6785-F7E5-4B1C-9B88-20111FC6D339} = {B5AE0988-6E25-434B-894A-06C6ED968EFF} 86 | EndGlobalSection 87 | GlobalSection(ExtensibilityGlobals) = postSolution 88 | SolutionGuid = {4F54DC7D-EA2B-4DE9-A6A1-EE3466C5FC11} 89 | EndGlobalSection 90 | EndGlobal 91 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Order.API/Controllers/OrdersController.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.AspNetCore.Mvc; 4 | using OutboxExample.Application.Features.Commands.CreateOrder; 5 | 6 | namespace OutboxExample.Order.API.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class OrdersController : ControllerBase 11 | { 12 | IMediator _mediator; 13 | public OrdersController(IMediator mediator) 14 | { 15 | _mediator = mediator; 16 | } 17 | 18 | [HttpPost] 19 | public async Task Post(CreateOrderCommandRequest createOrderCommandRequest) 20 | { 21 | return Ok(await _mediator.Send(createOrderCommandRequest)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Order.API/OutboxExample.Order.API.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | all 12 | runtime; build; native; contentfiles; analyzers; buildtransitive 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Order.API/Program.cs: -------------------------------------------------------------------------------- 1 | using OutboxExample.Persistence; 2 | using OutboxExample.Application; 3 | 4 | var builder = WebApplication.CreateBuilder(args); 5 | 6 | builder.Services.AddPersistenceServices(); 7 | builder.Services.AddApplicationServices(); 8 | builder.Services.AddControllers(); 9 | builder.Services.AddEndpointsApiExplorer(); 10 | builder.Services.AddSwaggerGen(); 11 | 12 | var app = builder.Build(); 13 | 14 | // Configure the HTTP request pipeline. 15 | if (app.Environment.IsDevelopment()) 16 | { 17 | app.UseSwagger(); 18 | app.UseSwaggerUI(); 19 | } 20 | 21 | app.UseHttpsRedirection(); 22 | 23 | app.UseAuthorization(); 24 | 25 | app.MapControllers(); 26 | 27 | app.Run(); 28 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Order.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:49326", 8 | "sslPort": 44374 9 | } 10 | }, 11 | "profiles": { 12 | "OutboxExample.Order.API": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7224;http://localhost:5224", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Order.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Order.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Stock.API/Consumers/OrderCreatedEventConsumer.cs: -------------------------------------------------------------------------------- 1 | using MassTransit; 2 | using OutboxExample.Application.Repositories; 3 | using OutboxExample.Domain.Entities; 4 | using OutboxExample.Shared.Events; 5 | 6 | namespace OutboxExample.Stock.API.Consumers 7 | { 8 | public class OrderCreatedEventConsumer : IConsumer 9 | { 10 | readonly IOrderInboxRepository _orderInboxRepository; 11 | 12 | public OrderCreatedEventConsumer(IOrderInboxRepository orderInboxRepository) 13 | { 14 | _orderInboxRepository = orderInboxRepository; 15 | } 16 | 17 | public async Task Consume(ConsumeContext context) 18 | { 19 | bool hasData = _orderInboxRepository.GetWhere(oi => oi.IdempotentToken == context.Message.IdempotentToken && oi.Processed).Any(); 20 | /* 21 | hasData : true ise demek ki bu event önceden gelmiş ve başarıyla işlenmiş lakin publisher tarafından gönderildiğine 22 | dair güncelleme işlemi bilinmeyen bir sebepten dolayı gerçekleştirilemediği için tekrardan 23 | publish edilmiştir. İşte idempotent özelliği sayesinde bu event'in tekrar işlenmesinin önüne böylece geçilmektedir. 24 | */ 25 | 26 | if (!hasData) 27 | { 28 | await _orderInboxRepository.AddAsync(new() 29 | { 30 | Description = context.Message.Description, 31 | IdempotentToken = context.Message.IdempotentToken, 32 | OrderId = context.Message.OrderId, 33 | Quantity = context.Message.Quantity, 34 | Processed = false 35 | }); 36 | await _orderInboxRepository.SaveChangesAsync(); 37 | } 38 | 39 | //Inbox table'a kaydedilen mesaj/event çekilip işleme tabi tutulmaktadır. 40 | 41 | List orderInboxes = _orderInboxRepository.GetWhere(oi => !oi.Processed).ToList(); 42 | foreach (var orderInbox in orderInboxes) 43 | { 44 | Console.WriteLine(@$"OrderId : {orderInbox.OrderId} 45 | Id : {orderInbox.IdempotentToken} 46 | Stock {orderInbox.Quantity} miktar kadar düşürülmüştür!"); 47 | orderInbox.Processed = true; 48 | } 49 | await _orderInboxRepository.SaveChangesAsync(); 50 | 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Stock.API/OutboxExample.Stock.API.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Stock.API/Program.cs: -------------------------------------------------------------------------------- 1 | using MassTransit; 2 | using OutboxExample.Application; 3 | using OutboxExample.Persistence; 4 | using OutboxExample.Stock.API.Consumers; 5 | 6 | var builder = WebApplication.CreateBuilder(args); 7 | 8 | 9 | builder.Services.AddPersistenceServices(); 10 | builder.Services.AddApplicationServices(); 11 | 12 | builder.Services.AddMassTransit(configurator => 13 | { 14 | configurator.AddConsumer(); 15 | configurator.UsingRabbitMq((context, _configurator) => 16 | { 17 | _configurator.Host(builder.Configuration["RabbitMQ:Host"], "/", hostConfigurator => 18 | { 19 | hostConfigurator.Username(builder.Configuration["RabbitMQ:Username"]); 20 | hostConfigurator.Password(builder.Configuration["RabbitMQ:Password"]); 21 | }); 22 | _configurator.ReceiveEndpoint("stock-order-created-event", e => e.ConfigureConsumer(context)); 23 | }); 24 | }); 25 | 26 | builder.Services.AddControllers(); 27 | builder.Services.AddEndpointsApiExplorer(); 28 | builder.Services.AddSwaggerGen(); 29 | 30 | var app = builder.Build(); 31 | 32 | if (app.Environment.IsDevelopment()) 33 | { 34 | app.UseSwagger(); 35 | app.UseSwaggerUI(); 36 | } 37 | 38 | app.UseHttpsRedirection(); 39 | 40 | app.UseAuthorization(); 41 | 42 | app.MapControllers(); 43 | 44 | app.Run(); 45 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Stock.API/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:49262", 8 | "sslPort": 44374 9 | } 10 | }, 11 | "profiles": { 12 | "OutboxExample.Stock.API": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": false, 16 | "launchUrl": "swagger", 17 | "applicationUrl": "https://localhost:7225;http://localhost:5225", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | }, 22 | "IIS Express": { 23 | "commandName": "IISExpress", 24 | "launchBrowser": true, 25 | "launchUrl": "swagger", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Stock.API/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Presentation/OutboxExample.Stock.API/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*", 9 | "RabbitMQ": { 10 | "Host": "localhost", 11 | "Username": "admin", 12 | "Password": "123456" 13 | }, 14 | "ConnectionStrings": { 15 | "SQLServer": "Server=localhost, 1433;Database=OutboxExampleDB;User ID=SA;Password=1q2w3e4r+!;" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /TransactionLogService/OutboxExample.TransactionLog.Service/OutboxExample.TransactionLog.Service.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /TransactionLogService/OutboxExample.TransactionLog.Service/Program.cs: -------------------------------------------------------------------------------- 1 | using Confluent.Kafka; 2 | 3 | ConsumerConfig config = new() 4 | { 5 | GroupId = "MSSQLServer.dbo.OrderOutboxes", 6 | BootstrapServers = "localhost:29092", 7 | AutoOffsetReset = AutoOffsetReset.Earliest 8 | }; 9 | 10 | using IConsumer consumer = new ConsumerBuilder(config).Build(); 11 | consumer.Subscribe("MSSQLServer.dbo.OrderOutboxes"); 12 | 13 | 14 | while (true) 15 | { 16 | CancellationTokenSource cancellationTokenSource = new(); 17 | ConsumeResult result = consumer.Consume(cancellationTokenSource.Token); 18 | 19 | Console.WriteLine(result.Value); 20 | /* 21 | Şu aşamadan sonra result.Value'da ki veriler ayıklanıp message broker'a gönderilebilir. 22 | */ 23 | } -------------------------------------------------------------------------------- /TransactionLogService/docker-compose-sqlserver.yaml: -------------------------------------------------------------------------------- 1 | version: '3.1' 2 | services: 3 | zookeeper: 4 | image: debezium/zookeeper 5 | ports: 6 | - "2181:2181" 7 | - "2888:2888" 8 | - "3888:3888" 9 | kafka: 10 | image: debezium/kafka 11 | ports: 12 | - "9092:9092" 13 | - "29092:29092" 14 | depends_on: 15 | - zookeeper 16 | environment: 17 | - ZOOKEEPER_CONNECT=zookeeper:2181 18 | - KAFKA_ADVERTISED_LISTENERS=LISTENER_EXT://localhost:29092,LISTENER_INT://kafka:9092 19 | - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP=LISTENER_INT:PLAINTEXT,LISTENER_EXT:PLAINTEXT 20 | - KAFKA_LISTENERS=LISTENER_INT://0.0.0.0:9092,LISTENER_EXT://0.0.0.0:29092 21 | - KAFKA_INTER_BROKER_LISTENER_NAME=LISTENER_INT 22 | connect: 23 | image: debezium/connect 24 | ports: 25 | - 8083:8083 26 | environment: 27 | - BOOTSTRAP_SERVERS=kafka:9092 28 | - GROUP_ID=1 29 | - CONFIG_STORAGE_TOPIC=my_connect_configs 30 | - OFFSET_STORAGE_TOPIC=my_connect_offsets 31 | - STATUS_STORAGE_TOPIC=my_connect_statuses 32 | depends_on: 33 | - zookeeper 34 | - kafka -------------------------------------------------------------------------------- /TransactionLogService/register-sqlserver.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "OutboxExample-Connector", 3 | "config": { 4 | "connector.class": "io.debezium.connector.sqlserver.SqlServerConnector", 5 | "tasks.max": "1", 6 | "database.hostname": "host.docker.internal", 7 | "database.port": "1433", 8 | "database.user": "SA", 9 | "database.password": "1q2w3e4r+!", 10 | "database.dbname": "OutboxExampleDB", 11 | "database.server.name": "MSSQLServer", 12 | "schema.include.list": "dbo", 13 | "table.whitelist": "dbo.OrderOutboxes", 14 | "database.history.kafka.bootstrap.servers": "kafka:9092", 15 | "database.history.kafka.topic": "dbhistory.outboxtable" 16 | } 17 | } -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/Contexts/OrderSingletonDatabase.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Microsoft.Data.SqlClient; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Data; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace OutboxExample.ProcessOutboxJob.Service.Contexts 11 | { 12 | public static class OrderSingletonDatabase 13 | { 14 | static OrderSingletonDatabase() 15 | { 16 | _connection = new SqlConnection("Server=localhost, 1433;Database=OutboxExampleDB;User ID=SA;Password=1q2w3e4r+!;"); 17 | } 18 | 19 | static IDbConnection _connection; 20 | public static IDbConnection Connection 21 | { 22 | get 23 | { 24 | if (_connection.State == ConnectionState.Closed) 25 | _connection.Open(); 26 | return _connection; 27 | } 28 | } 29 | 30 | public static async Task> QueryAsync(string sql) 31 | => await _connection.QueryAsync(sql); 32 | public static async Task ExecuteAsync(string sql) 33 | => await _connection.ExecuteAsync(sql); 34 | 35 | static bool _dataReaderState = true; 36 | public static bool DataReaderState { get => _dataReaderState; } 37 | 38 | public static void DataReaderReady() => _dataReaderState = true; 39 | public static void DataReaderBusy() => _dataReaderState = false; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/Jobs/OrderOutboxPublishJob.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using MassTransit; 3 | using OutboxExample.Domain.Entities; 4 | using OutboxExample.ProcessOutboxJob.Service.Contexts; 5 | using OutboxExample.Shared.Events; 6 | using Quartz; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Text; 11 | using System.Text.Json; 12 | using System.Threading.Tasks; 13 | 14 | namespace OutboxExample.ProcessOutboxJob.Service.Jobs 15 | { 16 | public class OrderOutboxPublishJob : IJob 17 | { 18 | readonly IPublishEndpoint _publishEndpoint; 19 | 20 | public OrderOutboxPublishJob(IPublishEndpoint publishEndpoint) 21 | { 22 | _publishEndpoint = publishEndpoint; 23 | } 24 | 25 | public async Task Execute(IJobExecutionContext context) 26 | { 27 | if (OrderSingletonDatabase.DataReaderState) 28 | { 29 | OrderSingletonDatabase.DataReaderBusy(); 30 | List orderOutboxes = (await OrderSingletonDatabase.QueryAsync($@"SELECT * FROM OrderOutboxes 31 | WHERE ProcessedDate IS NULL 32 | ORDER By OccuredOn DESC")) 33 | .ToList(); 34 | foreach (OrderOutbox orderOutbox in orderOutboxes) 35 | { 36 | if (orderOutbox.Type == nameof(OrderCreatedEvent)) 37 | { 38 | Order? order = JsonSerializer.Deserialize(orderOutbox.Payload); 39 | if (order != null) 40 | { 41 | OrderCreatedEvent orderCreatedEvent = new() 42 | { 43 | Description = order.Description, 44 | OrderId = order.Id, 45 | Quantity = order.Quantity, 46 | IdempotentToken = orderOutbox.IdempotentToken 47 | }; 48 | 49 | await _publishEndpoint.Publish(orderCreatedEvent); 50 | } 51 | } 52 | 53 | /* 54 | Outbox table'da ki publish edilmemiş mesajları/event'leri message 55 | broker'a publish ettik. Şimdi yayınlanmış bu mesajların yayınlandığına 56 | dair veritabanında Outbox table'da gerekli güncellemelerin/işaretlemelerin 57 | yapılması gerekmektedir(ya da yayınlanmış mesaja dair kayıt silinmelidir) 58 | İşte tam bu noktada Outbox table'ın olduğu veritabanı ile yaşanabilecek 59 | olası bağlantı kopukluklarından dolayı Idempotent tasarımı kullanıyor olacağız. 60 | Çünkü bir sonraki job'ın tetiklenme sürecinde bu işlendiğine dair güncellenemeyen 61 | ama özünde işlenen mesajlar tekrardan/yineli bir şekilde message broker'a gönderilecek 62 | ve consumer tarafından veri tutarsızlığına meydan verebilecek şekilde tüketilecektir. 63 | Consumer gerektiği taktirde Inbox pattern'ın getirisi olan Inbox 64 | table'ı kullanarak hangi mesajları/event'leri işleyip işlemediğini tutacak ve 65 | ihtimal olarak yinelenebilecek mesajların tutarsızlığa sebebiyet verebilecek durumları 66 | böylece engellenmiş olacaktır. 67 | */ 68 | int result = await OrderSingletonDatabase.ExecuteAsync(@$"UPDATE OrderOutboxes SET ProcessedDate = GETDATE() 69 | WHERE IdempotentToken = '{orderOutbox.IdempotentToken}'"); 70 | 71 | } 72 | OrderSingletonDatabase.DataReaderReady(); 73 | Console.WriteLine("Order outbox table checked!"); 74 | } 75 | 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/OutboxExample.ProcessOutboxJob.Service.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0 5 | enable 6 | enable 7 | dotnet-OutboxExample.ProcessOutboxJob.Service-1314D49C-303D-40C6-8DC9-F0A457E742E4 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/Program.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gncyyldz/Outbox-Design-Pattern-Example/cb4808c71fc39fd33ef17453ed6d98980760fc91/Worker/OutboxExample.ProcessOutboxJob.Service/Program.cs -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "OutboxExample.ProcessOutboxJob.Service": { 4 | "commandName": "Project", 5 | "dotnetRunMessages": true, 6 | "environmentVariables": { 7 | "DOTNET_ENVIRONMENT": "Development" 8 | } 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Worker/OutboxExample.ProcessOutboxJob.Service/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.Hosting.Lifetime": "Information" 6 | } 7 | }, 8 | "RabbitMQ": { 9 | "Host": "localhost", 10 | "Username": "admin", 11 | "Password": "123456" 12 | }, 13 | "ConnectionStrings": { 14 | "SQLServer": "Server=localhost, 1433;Database=OutboxExampleDB;User ID=SA;Password=1q2w3e4r+!;" 15 | } 16 | } 17 | --------------------------------------------------------------------------------