├── .gitignore ├── DDDMart.sln ├── README.md ├── src ├── Catalogue │ ├── DDDMart.Catalogue.Application │ │ ├── AutofacModules │ │ │ └── CatalogueApplicationModule.cs │ │ ├── DDDMart.Catalogue.Application.csproj │ │ └── Services │ │ │ └── CatalogueIntegrationEventMapper.cs │ ├── DDDMart.Catalogue.Core │ │ ├── DDDMart.Catalogue.Core.csproj │ │ ├── ICatalogueIntegrationEventMapper.cs │ │ ├── Products │ │ │ ├── Entities │ │ │ │ └── Product.cs │ │ │ ├── Repositories │ │ │ │ └── IProductsRepository.cs │ │ │ └── ValueObjects │ │ │ │ ├── Picture.cs │ │ │ │ └── ProductInfo.cs │ │ └── Reviews │ │ │ ├── DomainEvents │ │ │ ├── ReviewCreatedDomainEvent.cs │ │ │ ├── ReviewResponseCreatedDomainEvent.cs │ │ │ └── ReviewUpdatedDomainEvent.cs │ │ │ ├── Entities │ │ │ ├── Review.cs │ │ │ └── ReviewResponse.cs │ │ │ └── ValueObjects │ │ │ ├── Comment.cs │ │ │ ├── Customer.cs │ │ │ └── Rating.cs │ └── DDDMart.Catalogue.Infrastructure │ │ ├── AutofacModules │ │ └── CatalogueInfrastructureModule.cs │ │ ├── CatalogueContext.cs │ │ ├── Configurations │ │ └── ProductConfiguration.cs │ │ ├── DDDMart.Catalogue.Infrastructure.csproj │ │ └── Repositories │ │ └── ProductsRepository.cs ├── Common │ ├── DDDMart.Application │ │ ├── AutofacModules │ │ │ └── EventBusModule.cs │ │ ├── DDDMart.Application.csproj │ │ ├── EventBus │ │ │ ├── HandlerSubscription.cs │ │ │ ├── IEventBus.cs │ │ │ ├── ISubscriptionContainer.cs │ │ │ ├── InMemoryEventBus.cs │ │ │ ├── Message.cs │ │ │ └── SubscriptionContainer.cs │ │ ├── Factories │ │ │ └── IntegrationEventFactory.cs │ │ ├── IIntegrationEventHandler.cs │ │ └── IntegrationEventMapper.cs │ ├── DDDMart.Infrastructure │ │ ├── DDDMart.Infrastructure.csproj │ │ ├── DbContextBase.cs │ │ ├── Extensions │ │ │ └── MediatorExtensions.cs │ │ └── Repositories │ │ │ └── Repository.cs │ └── DDDMart.SharedKernel │ │ ├── AggregateRoot.cs │ │ ├── DDDMart.SharedKernel.csproj │ │ ├── DomainEvent.cs │ │ ├── DomainEventHandler.cs │ │ ├── Entity.cs │ │ ├── Exceptions │ │ ├── DomainException.cs │ │ └── NotFoundException.cs │ │ ├── Guards │ │ ├── Guard.cs │ │ ├── GuardAgainstLengthExtensions.cs │ │ ├── GuardAgainstNullExtensions.cs │ │ ├── GuardAgainstNumberExtensions.cs │ │ ├── GuardAgainstUrlExtensions.cs │ │ └── GuardClauseExtensions.cs │ │ ├── IRepository.cs │ │ ├── IUnitOfWork.cs │ │ ├── IntegrationEvent.cs │ │ ├── IsExternalInit.cs │ │ ├── Outbox │ │ ├── Entities │ │ │ └── OutboxIntegrationEvent.cs │ │ ├── Factories │ │ │ └── IIntegrationEventFactory.cs │ │ └── Services │ │ │ └── IIntegrationEventMapper.cs │ │ ├── ValueObject.cs │ │ └── ValueObjects │ │ └── Address.cs ├── DDDMart │ ├── DDDMart.csproj │ ├── IntegrationEventPublisher.cs │ ├── IntegrationEventsService.cs │ ├── OrderGenerator.cs │ └── Program.cs ├── Ordering │ ├── DDDMart.Ordering.Application │ │ ├── AutofacModules │ │ │ └── OrderingApplicationModule.cs │ │ ├── DDDMart.Ordering.Application.csproj │ │ ├── IntegrationEvents │ │ │ ├── Handlers │ │ │ │ └── InvoicePaidIntegrationEventHandler.cs │ │ │ ├── InvoicePaidIntegrationEvent.cs │ │ │ ├── OrderCancelledIntegrationEvent.cs │ │ │ └── OrderSubmittedIntegrationEvent.cs │ │ └── Services │ │ │ └── OrderingIntegrationEventMapper.cs │ ├── DDDMart.Ordering.Core │ │ ├── AutofacModules │ │ │ └── OrderingCoreModule.cs │ │ ├── Baskets │ │ │ ├── DomainEvents │ │ │ │ └── BasketCheckedOutDomainEvent.cs │ │ │ ├── Entities │ │ │ │ ├── Basket.cs │ │ │ │ └── BasketItem.cs │ │ │ └── Repositories │ │ │ │ └── IBasketsRepository.cs │ │ ├── Common │ │ │ └── ValueObjects │ │ │ │ └── OrderProduct.cs │ │ ├── DDDMart.Ordering.Core.csproj │ │ ├── IOrderingIntegrationEventMapper.cs │ │ └── Orders │ │ │ ├── DomainEventHandlers │ │ │ └── BasketCheckedOutDomainEventHandler.cs │ │ │ ├── DomainEvents │ │ │ ├── OrderCancelledDomainEvent.cs │ │ │ ├── OrderDispatchedDomainEvent.cs │ │ │ └── OrderSubmittedDomainEvent.cs │ │ │ ├── Entities │ │ │ ├── Order.cs │ │ │ └── OrderItem.cs │ │ │ ├── Factories │ │ │ └── AddressFactory.cs │ │ │ ├── Repositories │ │ │ └── IOrdersRepository.cs │ │ │ └── ValueObjects │ │ │ ├── OrderStatus.cs │ │ │ ├── PaymentAddress.cs │ │ │ └── ShippingAddress.cs │ └── DDDMart.Ordering.Infrastructure │ │ ├── AutofacModules │ │ └── OrderingInfrastructureModule.cs │ │ ├── Configurations │ │ ├── BasketConfiguration.cs │ │ └── OrderConfiguration.cs │ │ ├── DDDMart.Ordering.Infrastructure.csproj │ │ ├── OrderingContext.cs │ │ └── Repositories │ │ ├── BasketsRepository.cs │ │ └── OrdersRepository.cs └── Payments │ ├── DDDMart.Payments.Application │ ├── AutofacModules │ │ └── PaymentsApplicationModule.cs │ ├── DDDMart.Payments.Application.csproj │ ├── IntegrationEvents │ │ ├── Handlers │ │ │ └── OrderSubmittedIntegrationEventHandler.cs │ │ ├── InvoicePaidIntegrationEvent.cs │ │ └── OrderSubmittedIntegrationEvent.cs │ └── Services │ │ └── PaymentsIntegrationEventMapper.cs │ ├── DDDMart.Payments.Core │ ├── DDDMart.Payments.Core.csproj │ ├── IPaymentsIntegrationEventMapper.cs │ ├── Invoices │ │ ├── DomainEvents │ │ │ └── InvoicePaidDomainEvent.cs │ │ ├── Entities │ │ │ └── Invoice.cs │ │ ├── Repositories │ │ │ └── IInvoicesRepository.cs │ │ └── ValueObjects │ │ │ ├── InvoiceAddress.cs │ │ │ └── InvoiceStatus.cs │ └── PaymentMethods │ │ ├── Entities │ │ └── PaymentMethod.cs │ │ ├── Repositories │ │ └── IPaymentMethodsRepository.cs │ │ └── ValueObjects │ │ ├── PaymentMethodStatus.cs │ │ └── PaymentType.cs │ └── DDDMart.Payments.Infrastructure │ ├── AutofacModules │ └── PaymentsInfrastructureModule.cs │ ├── Configurations │ ├── InvoiceConfiguration.cs │ └── PaymentMethodConfiguration.cs │ ├── DDDMart.Payments.Infrastructure.csproj │ ├── PaymentsContext.cs │ └── Repositories │ ├── InvoicesRepository.cs │ └── PaymentMethodsRepository.cs └── tests ├── Catalogue └── DDDMart.Catalogue.Core.Tests │ ├── Builders │ ├── ProductBuilder.cs │ └── ReviewBuilder.cs │ ├── DDDMart.Catalogue.Core.Tests.csproj │ ├── GlobalUsings.cs │ ├── Products │ ├── Entities │ │ └── ProductTests.cs │ └── ValueObjects │ │ ├── PictureTests.cs │ │ └── ProductInfoTests.cs │ └── Reviews │ └── Entities │ └── ReviewTests.cs ├── DDDMart.Core.Tests ├── DDDMart.Core.Tests.csproj └── StringGenerator.cs ├── Ordering ├── DDDMart.Ordering.Core.Tests │ ├── Baskets │ │ └── Entities │ │ │ └── BasketTests.cs │ ├── Builders │ │ ├── AddressBuilder.cs │ │ ├── BasketBuilder.cs │ │ └── OrderBuilder.cs │ ├── DDDMart.Ordering.Core.Tests.csproj │ ├── GlobalUsings.cs │ └── Orders │ │ ├── DomainEventHandlers │ │ └── BasketCheckedOutDomainEventHandlerTests.cs │ │ └── Entities │ │ └── OrderTests.cs └── DDDMart.Ordering.Infrastructure.Tests │ ├── DDDMart.Ordering.Infrastructure.Tests.csproj │ ├── GlobalUsings.cs │ └── Repositories │ └── OrdersRepositoryTests.cs └── Payments ├── DDDMart.Payments.Application.Tests ├── DDDMart.Payments.Application.Tests.csproj ├── GlobalUsings.cs ├── IntegrationEventHandlers │ └── OrderSubmittedIntegrationEventHandlerTests.cs └── Services │ └── PaymentsIntegrationEventMapperTests.cs └── DDDMart.Payments.Core.Tests ├── Builders ├── InvoiceBuilder.cs └── PaymentMethodBuilder.cs ├── DDDMart.Payments.Core.Tests.csproj ├── GlobalUsings.cs ├── Invoices └── Entities │ └── InvoiceTests.cs └── PaymentMethods └── Entities └── PaymentMethodTests.cs /.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 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /DDDMart.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.1.32328.378 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart", "src\DDDMart\DDDMart.csproj", "{E33C308B-844C-456E-B2F0-92E82C224CD0}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "_SolutionItems", "_SolutionItems", "{1B78AD18-2ECF-4CD6-BC77-114D49EC0551}" 9 | ProjectSection(SolutionItems) = preProject 10 | README.md = README.md 11 | EndProjectSection 12 | EndProject 13 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{A403C39E-25CD-4FC0-BD2F-E1061674F90B}" 14 | EndProject 15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Catalogue", "Catalogue", "{4D23C550-C831-4DA2-AEEA-7DFD431577ED}" 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Ordering", "Ordering", "{F3DD0045-4EAA-4F9F-BB1D-2819DC40B544}" 18 | EndProject 19 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Payments", "Payments", "{E750A5A2-FDAF-4898-B2BF-47B37C78D90D}" 20 | EndProject 21 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Catalogue.Core", "src\Catalogue\DDDMart.Catalogue.Core\DDDMart.Catalogue.Core.csproj", "{4540E389-ACD7-4DFC-A441-B12356FFF719}" 22 | EndProject 23 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.SharedKernel", "src\Common\DDDMart.SharedKernel\DDDMart.SharedKernel.csproj", "{E1BA0F62-779E-4F23-8650-E1FD3A65EAB2}" 24 | EndProject 25 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Catalogue.Infrastructure", "src\Catalogue\DDDMart.Catalogue.Infrastructure\DDDMart.Catalogue.Infrastructure.csproj", "{575B3A80-214E-4F18-9A80-742F1696F49A}" 26 | EndProject 27 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Infrastructure", "src\Common\DDDMart.Infrastructure\DDDMart.Infrastructure.csproj", "{EF5D5E5B-8341-4E07-8D23-99AD1E0F2C6A}" 28 | EndProject 29 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Ordering.Core", "src\Ordering\DDDMart.Ordering.Core\DDDMart.Ordering.Core.csproj", "{B25FEE20-ADC1-4DD4-B5F3-D6DD08CF87D2}" 30 | EndProject 31 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Ordering.Infrastructure", "src\Ordering\DDDMart.Ordering.Infrastructure\DDDMart.Ordering.Infrastructure.csproj", "{9713D119-77BA-4881-B366-AFFD6BC3B05D}" 32 | EndProject 33 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Payments.Core", "src\Payments\DDDMart.Payments.Core\DDDMart.Payments.Core.csproj", "{A4895600-F5C2-44EC-89A5-E3626B4663DC}" 34 | EndProject 35 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Payments.Infrastructure", "src\Payments\DDDMart.Payments.Infrastructure\DDDMart.Payments.Infrastructure.csproj", "{AEC7D730-1A9D-46E6-920E-CE0FDEBDD127}" 36 | EndProject 37 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Application", "src\Common\DDDMart.Application\DDDMart.Application.csproj", "{EAAAFEEA-88AB-45A9-80AF-A2F517908302}" 38 | EndProject 39 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Ordering.Application", "src\Ordering\DDDMart.Ordering.Application\DDDMart.Ordering.Application.csproj", "{1E7788E0-1C00-46DB-9A50-073094CA3A74}" 40 | EndProject 41 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Payments.Application", "src\Payments\DDDMart.Payments.Application\DDDMart.Payments.Application.csproj", "{840CB011-AE76-4B61-8FEE-1AFF39016D0D}" 42 | EndProject 43 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Catalogue.Application", "src\Catalogue\DDDMart.Catalogue.Application\DDDMart.Catalogue.Application.csproj", "{F942217E-05A3-4523-903C-1CBBFE05BE4D}" 44 | EndProject 45 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Common", "Common", "{18401257-9D59-455F-A60E-FE9DE3068638}" 46 | EndProject 47 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{EACB01FE-4E72-43E8-AFE6-98C7B43B5987}" 48 | EndProject 49 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Ordering", "Ordering", "{D7588687-C20C-4A47-AD76-5889DBBE9CAD}" 50 | EndProject 51 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Ordering.Core.Tests", "tests\Ordering\DDDMart.Ordering.Core.Tests\DDDMart.Ordering.Core.Tests.csproj", "{6174060F-8153-44F1-B74D-2DF3F8A293EB}" 52 | EndProject 53 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Catalogue", "Catalogue", "{FA723BA1-C44C-44A7-93B8-878E51DFB6F2}" 54 | EndProject 55 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Catalogue.Core.Tests", "tests\Catalogue\DDDMart.Catalogue.Core.Tests\DDDMart.Catalogue.Core.Tests.csproj", "{9478D4BE-510D-49C4-92D0-E32BFD2E1E34}" 56 | EndProject 57 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Payments", "Payments", "{7AB75DD6-8CFA-4261-A6D0-008CDB19F056}" 58 | EndProject 59 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Payments.Core.Tests", "tests\Payments\DDDMart.Payments.Core.Tests\DDDMart.Payments.Core.Tests.csproj", "{4D25A5FA-CC53-49E6-A338-CDE74E19617B}" 60 | EndProject 61 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Payments.Application.Tests", "tests\Payments\DDDMart.Payments.Application.Tests\DDDMart.Payments.Application.Tests.csproj", "{6FDA72CD-5745-4DC4-BC00-5F9F99B5D3BC}" 62 | EndProject 63 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DDDMart.Ordering.Infrastructure.Tests", "tests\Ordering\DDDMart.Ordering.Infrastructure.Tests\DDDMart.Ordering.Infrastructure.Tests.csproj", "{B4B22637-285F-4AD6-9320-CD934BD260D4}" 64 | EndProject 65 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DDDMart.Core.Tests", "tests\DDDMart.Core.Tests\DDDMart.Core.Tests.csproj", "{343C6BE3-EAE7-4F24-B894-F11ADF22BB61}" 66 | EndProject 67 | Global 68 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 69 | Debug|Any CPU = Debug|Any CPU 70 | Release|Any CPU = Release|Any CPU 71 | EndGlobalSection 72 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 73 | {E33C308B-844C-456E-B2F0-92E82C224CD0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 74 | {E33C308B-844C-456E-B2F0-92E82C224CD0}.Debug|Any CPU.Build.0 = Debug|Any CPU 75 | {E33C308B-844C-456E-B2F0-92E82C224CD0}.Release|Any CPU.ActiveCfg = Release|Any CPU 76 | {E33C308B-844C-456E-B2F0-92E82C224CD0}.Release|Any CPU.Build.0 = Release|Any CPU 77 | {4540E389-ACD7-4DFC-A441-B12356FFF719}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 78 | {4540E389-ACD7-4DFC-A441-B12356FFF719}.Debug|Any CPU.Build.0 = Debug|Any CPU 79 | {4540E389-ACD7-4DFC-A441-B12356FFF719}.Release|Any CPU.ActiveCfg = Release|Any CPU 80 | {4540E389-ACD7-4DFC-A441-B12356FFF719}.Release|Any CPU.Build.0 = Release|Any CPU 81 | {E1BA0F62-779E-4F23-8650-E1FD3A65EAB2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 82 | {E1BA0F62-779E-4F23-8650-E1FD3A65EAB2}.Debug|Any CPU.Build.0 = Debug|Any CPU 83 | {E1BA0F62-779E-4F23-8650-E1FD3A65EAB2}.Release|Any CPU.ActiveCfg = Release|Any CPU 84 | {E1BA0F62-779E-4F23-8650-E1FD3A65EAB2}.Release|Any CPU.Build.0 = Release|Any CPU 85 | {575B3A80-214E-4F18-9A80-742F1696F49A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 86 | {575B3A80-214E-4F18-9A80-742F1696F49A}.Debug|Any CPU.Build.0 = Debug|Any CPU 87 | {575B3A80-214E-4F18-9A80-742F1696F49A}.Release|Any CPU.ActiveCfg = Release|Any CPU 88 | {575B3A80-214E-4F18-9A80-742F1696F49A}.Release|Any CPU.Build.0 = Release|Any CPU 89 | {EF5D5E5B-8341-4E07-8D23-99AD1E0F2C6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 90 | {EF5D5E5B-8341-4E07-8D23-99AD1E0F2C6A}.Debug|Any CPU.Build.0 = Debug|Any CPU 91 | {EF5D5E5B-8341-4E07-8D23-99AD1E0F2C6A}.Release|Any CPU.ActiveCfg = Release|Any CPU 92 | {EF5D5E5B-8341-4E07-8D23-99AD1E0F2C6A}.Release|Any CPU.Build.0 = Release|Any CPU 93 | {B25FEE20-ADC1-4DD4-B5F3-D6DD08CF87D2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 94 | {B25FEE20-ADC1-4DD4-B5F3-D6DD08CF87D2}.Debug|Any CPU.Build.0 = Debug|Any CPU 95 | {B25FEE20-ADC1-4DD4-B5F3-D6DD08CF87D2}.Release|Any CPU.ActiveCfg = Release|Any CPU 96 | {B25FEE20-ADC1-4DD4-B5F3-D6DD08CF87D2}.Release|Any CPU.Build.0 = Release|Any CPU 97 | {9713D119-77BA-4881-B366-AFFD6BC3B05D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 98 | {9713D119-77BA-4881-B366-AFFD6BC3B05D}.Debug|Any CPU.Build.0 = Debug|Any CPU 99 | {9713D119-77BA-4881-B366-AFFD6BC3B05D}.Release|Any CPU.ActiveCfg = Release|Any CPU 100 | {9713D119-77BA-4881-B366-AFFD6BC3B05D}.Release|Any CPU.Build.0 = Release|Any CPU 101 | {A4895600-F5C2-44EC-89A5-E3626B4663DC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 102 | {A4895600-F5C2-44EC-89A5-E3626B4663DC}.Debug|Any CPU.Build.0 = Debug|Any CPU 103 | {A4895600-F5C2-44EC-89A5-E3626B4663DC}.Release|Any CPU.ActiveCfg = Release|Any CPU 104 | {A4895600-F5C2-44EC-89A5-E3626B4663DC}.Release|Any CPU.Build.0 = Release|Any CPU 105 | {AEC7D730-1A9D-46E6-920E-CE0FDEBDD127}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 106 | {AEC7D730-1A9D-46E6-920E-CE0FDEBDD127}.Debug|Any CPU.Build.0 = Debug|Any CPU 107 | {AEC7D730-1A9D-46E6-920E-CE0FDEBDD127}.Release|Any CPU.ActiveCfg = Release|Any CPU 108 | {AEC7D730-1A9D-46E6-920E-CE0FDEBDD127}.Release|Any CPU.Build.0 = Release|Any CPU 109 | {EAAAFEEA-88AB-45A9-80AF-A2F517908302}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 110 | {EAAAFEEA-88AB-45A9-80AF-A2F517908302}.Debug|Any CPU.Build.0 = Debug|Any CPU 111 | {EAAAFEEA-88AB-45A9-80AF-A2F517908302}.Release|Any CPU.ActiveCfg = Release|Any CPU 112 | {EAAAFEEA-88AB-45A9-80AF-A2F517908302}.Release|Any CPU.Build.0 = Release|Any CPU 113 | {1E7788E0-1C00-46DB-9A50-073094CA3A74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 114 | {1E7788E0-1C00-46DB-9A50-073094CA3A74}.Debug|Any CPU.Build.0 = Debug|Any CPU 115 | {1E7788E0-1C00-46DB-9A50-073094CA3A74}.Release|Any CPU.ActiveCfg = Release|Any CPU 116 | {1E7788E0-1C00-46DB-9A50-073094CA3A74}.Release|Any CPU.Build.0 = Release|Any CPU 117 | {840CB011-AE76-4B61-8FEE-1AFF39016D0D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 118 | {840CB011-AE76-4B61-8FEE-1AFF39016D0D}.Debug|Any CPU.Build.0 = Debug|Any CPU 119 | {840CB011-AE76-4B61-8FEE-1AFF39016D0D}.Release|Any CPU.ActiveCfg = Release|Any CPU 120 | {840CB011-AE76-4B61-8FEE-1AFF39016D0D}.Release|Any CPU.Build.0 = Release|Any CPU 121 | {F942217E-05A3-4523-903C-1CBBFE05BE4D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 122 | {F942217E-05A3-4523-903C-1CBBFE05BE4D}.Debug|Any CPU.Build.0 = Debug|Any CPU 123 | {F942217E-05A3-4523-903C-1CBBFE05BE4D}.Release|Any CPU.ActiveCfg = Release|Any CPU 124 | {F942217E-05A3-4523-903C-1CBBFE05BE4D}.Release|Any CPU.Build.0 = Release|Any CPU 125 | {6174060F-8153-44F1-B74D-2DF3F8A293EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 126 | {6174060F-8153-44F1-B74D-2DF3F8A293EB}.Debug|Any CPU.Build.0 = Debug|Any CPU 127 | {6174060F-8153-44F1-B74D-2DF3F8A293EB}.Release|Any CPU.ActiveCfg = Release|Any CPU 128 | {6174060F-8153-44F1-B74D-2DF3F8A293EB}.Release|Any CPU.Build.0 = Release|Any CPU 129 | {9478D4BE-510D-49C4-92D0-E32BFD2E1E34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 130 | {9478D4BE-510D-49C4-92D0-E32BFD2E1E34}.Debug|Any CPU.Build.0 = Debug|Any CPU 131 | {9478D4BE-510D-49C4-92D0-E32BFD2E1E34}.Release|Any CPU.ActiveCfg = Release|Any CPU 132 | {9478D4BE-510D-49C4-92D0-E32BFD2E1E34}.Release|Any CPU.Build.0 = Release|Any CPU 133 | {4D25A5FA-CC53-49E6-A338-CDE74E19617B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 134 | {4D25A5FA-CC53-49E6-A338-CDE74E19617B}.Debug|Any CPU.Build.0 = Debug|Any CPU 135 | {4D25A5FA-CC53-49E6-A338-CDE74E19617B}.Release|Any CPU.ActiveCfg = Release|Any CPU 136 | {4D25A5FA-CC53-49E6-A338-CDE74E19617B}.Release|Any CPU.Build.0 = Release|Any CPU 137 | {6FDA72CD-5745-4DC4-BC00-5F9F99B5D3BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 138 | {6FDA72CD-5745-4DC4-BC00-5F9F99B5D3BC}.Debug|Any CPU.Build.0 = Debug|Any CPU 139 | {6FDA72CD-5745-4DC4-BC00-5F9F99B5D3BC}.Release|Any CPU.ActiveCfg = Release|Any CPU 140 | {6FDA72CD-5745-4DC4-BC00-5F9F99B5D3BC}.Release|Any CPU.Build.0 = Release|Any CPU 141 | {B4B22637-285F-4AD6-9320-CD934BD260D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 142 | {B4B22637-285F-4AD6-9320-CD934BD260D4}.Debug|Any CPU.Build.0 = Debug|Any CPU 143 | {B4B22637-285F-4AD6-9320-CD934BD260D4}.Release|Any CPU.ActiveCfg = Release|Any CPU 144 | {B4B22637-285F-4AD6-9320-CD934BD260D4}.Release|Any CPU.Build.0 = Release|Any CPU 145 | {343C6BE3-EAE7-4F24-B894-F11ADF22BB61}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 146 | {343C6BE3-EAE7-4F24-B894-F11ADF22BB61}.Debug|Any CPU.Build.0 = Debug|Any CPU 147 | {343C6BE3-EAE7-4F24-B894-F11ADF22BB61}.Release|Any CPU.ActiveCfg = Release|Any CPU 148 | {343C6BE3-EAE7-4F24-B894-F11ADF22BB61}.Release|Any CPU.Build.0 = Release|Any CPU 149 | EndGlobalSection 150 | GlobalSection(SolutionProperties) = preSolution 151 | HideSolutionNode = FALSE 152 | EndGlobalSection 153 | GlobalSection(NestedProjects) = preSolution 154 | {E33C308B-844C-456E-B2F0-92E82C224CD0} = {A403C39E-25CD-4FC0-BD2F-E1061674F90B} 155 | {4D23C550-C831-4DA2-AEEA-7DFD431577ED} = {A403C39E-25CD-4FC0-BD2F-E1061674F90B} 156 | {F3DD0045-4EAA-4F9F-BB1D-2819DC40B544} = {A403C39E-25CD-4FC0-BD2F-E1061674F90B} 157 | {E750A5A2-FDAF-4898-B2BF-47B37C78D90D} = {A403C39E-25CD-4FC0-BD2F-E1061674F90B} 158 | {4540E389-ACD7-4DFC-A441-B12356FFF719} = {4D23C550-C831-4DA2-AEEA-7DFD431577ED} 159 | {E1BA0F62-779E-4F23-8650-E1FD3A65EAB2} = {18401257-9D59-455F-A60E-FE9DE3068638} 160 | {575B3A80-214E-4F18-9A80-742F1696F49A} = {4D23C550-C831-4DA2-AEEA-7DFD431577ED} 161 | {EF5D5E5B-8341-4E07-8D23-99AD1E0F2C6A} = {18401257-9D59-455F-A60E-FE9DE3068638} 162 | {B25FEE20-ADC1-4DD4-B5F3-D6DD08CF87D2} = {F3DD0045-4EAA-4F9F-BB1D-2819DC40B544} 163 | {9713D119-77BA-4881-B366-AFFD6BC3B05D} = {F3DD0045-4EAA-4F9F-BB1D-2819DC40B544} 164 | {A4895600-F5C2-44EC-89A5-E3626B4663DC} = {E750A5A2-FDAF-4898-B2BF-47B37C78D90D} 165 | {AEC7D730-1A9D-46E6-920E-CE0FDEBDD127} = {E750A5A2-FDAF-4898-B2BF-47B37C78D90D} 166 | {EAAAFEEA-88AB-45A9-80AF-A2F517908302} = {18401257-9D59-455F-A60E-FE9DE3068638} 167 | {1E7788E0-1C00-46DB-9A50-073094CA3A74} = {F3DD0045-4EAA-4F9F-BB1D-2819DC40B544} 168 | {840CB011-AE76-4B61-8FEE-1AFF39016D0D} = {E750A5A2-FDAF-4898-B2BF-47B37C78D90D} 169 | {F942217E-05A3-4523-903C-1CBBFE05BE4D} = {4D23C550-C831-4DA2-AEEA-7DFD431577ED} 170 | {18401257-9D59-455F-A60E-FE9DE3068638} = {A403C39E-25CD-4FC0-BD2F-E1061674F90B} 171 | {D7588687-C20C-4A47-AD76-5889DBBE9CAD} = {EACB01FE-4E72-43E8-AFE6-98C7B43B5987} 172 | {6174060F-8153-44F1-B74D-2DF3F8A293EB} = {D7588687-C20C-4A47-AD76-5889DBBE9CAD} 173 | {FA723BA1-C44C-44A7-93B8-878E51DFB6F2} = {EACB01FE-4E72-43E8-AFE6-98C7B43B5987} 174 | {9478D4BE-510D-49C4-92D0-E32BFD2E1E34} = {FA723BA1-C44C-44A7-93B8-878E51DFB6F2} 175 | {7AB75DD6-8CFA-4261-A6D0-008CDB19F056} = {EACB01FE-4E72-43E8-AFE6-98C7B43B5987} 176 | {4D25A5FA-CC53-49E6-A338-CDE74E19617B} = {7AB75DD6-8CFA-4261-A6D0-008CDB19F056} 177 | {6FDA72CD-5745-4DC4-BC00-5F9F99B5D3BC} = {7AB75DD6-8CFA-4261-A6D0-008CDB19F056} 178 | {B4B22637-285F-4AD6-9320-CD934BD260D4} = {D7588687-C20C-4A47-AD76-5889DBBE9CAD} 179 | {343C6BE3-EAE7-4F24-B894-F11ADF22BB61} = {EACB01FE-4E72-43E8-AFE6-98C7B43B5987} 180 | EndGlobalSection 181 | GlobalSection(ExtensibilityGlobals) = postSolution 182 | SolutionGuid = {C8B94588-BF39-4AD5-817A-A5E769F78BC9} 183 | EndGlobalSection 184 | EndGlobal 185 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DDDMart 2 | 3 | This is a small sample application for a fake eCommerce company (**DDDMart**) which uses ***Domain Driven Design*** techniques for modelling the domain. 4 | 5 | The application focuses on the core Domain layer so does not have any APIs. There are a lot of different opinionated ways to host domain models through an API and I specifically wanted to focus on modelling the domain and how Domain and Integration events are handled. 6 | 7 | The **DDDMart** console application hosts a number of background services which are used to simulate how an **Order** is generated and paid using the different ***bounded contexts***. 8 | 9 | ## Sub-Domains 10 | 11 | The domain is made up of 3 sub-domains: 12 | - Catalogue (Core) - **Product** catalogue 13 | - Ordering (Core) - Used for creating a **Basket** and creating an **Order** of different Products 14 | - Payments (Supporting) - Used for generating and tracking **Invoices** and storing customer **Payment Methods** 15 | 16 | Each sub-domain is made up for 1 or more bounded-contexts. The application has been layer to allow each sub-domain to be hosted as a separate **microservice**. -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Application/AutofacModules/CatalogueApplicationModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using DDDMart.Catalogue.Application.Services; 3 | 4 | namespace DDDMart.Catalogue.Application.AutofacModules 5 | { 6 | public class CatalogueApplicationModule : Module 7 | { 8 | protected override void Load(ContainerBuilder builder) 9 | { 10 | builder.RegisterType() 11 | .AsImplementedInterfaces() 12 | .SingleInstance(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Application/DDDMart.Catalogue.Application.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Application/Services/CatalogueIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application; 2 | using DDDMart.Catalogue.Core; 3 | using DDDMart.SharedKernel; 4 | 5 | namespace DDDMart.Catalogue.Application.Services 6 | { 7 | public class CatalogueIntegrationEventMapper : IntegrationEventMapper, ICatalogueIntegrationEventMapper 8 | { 9 | protected override IntegrationEvent MapDomainEvent(T domainEvent) 10 | { 11 | return null; 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/DDDMart.Catalogue.Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/ICatalogueIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Outbox.Services; 2 | 3 | namespace DDDMart.Catalogue.Core 4 | { 5 | public interface ICatalogueIntegrationEventMapper : IIntegrationEventMapper 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Products/Entities/Product.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | using DDDMart.SharedKernel.Guards; 4 | 5 | namespace DDDMart.Catalogue.Core.Products.Entities 6 | { 7 | public class Product : AggregateRoot 8 | { 9 | private Product(ProductInfo info, string sicCode, decimal price, Picture picture) 10 | { 11 | Info = info; 12 | SicCode = sicCode; 13 | Price = price; 14 | Picture = picture; 15 | } 16 | 17 | private Product() 18 | { 19 | 20 | } 21 | 22 | public static Product Create(ProductInfo info, string sicCode, decimal price, Picture picture) 23 | { 24 | Guard.Against.LessThanZero(price, "Price"); 25 | Guard.Against.NullOrEmpty(sicCode, "Sic Code"); 26 | return new Product(info, sicCode, price, picture); 27 | } 28 | 29 | public ProductInfo Info { get; private set; } 30 | public string SicCode { get; private set; } 31 | public decimal Price { get; private set; } 32 | public Picture Picture { get; private set; } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Products/Repositories/IProductsRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.Entities; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Catalogue.Core.Products.Repositories 5 | { 6 | public interface IProductsRepository : IRepository 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Products/ValueObjects/Picture.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using DDDMart.SharedKernel.Guards; 3 | 4 | namespace DDDMart.Catalogue.Core.Products.ValueObjects 5 | { 6 | public class Picture : ValueObject 7 | { 8 | private Picture(string name, string uri) 9 | { 10 | Name = name; 11 | Uri = uri; 12 | } 13 | 14 | public static Picture Create(string name, string uri) 15 | { 16 | Guard.Against.NullOrEmpty(name, "Name"); 17 | Guard.Against.InvalidUrl(uri, "Uri"); 18 | return new Picture(name, uri); 19 | } 20 | 21 | public string Name { get; private set; } 22 | public string Uri { get; private set; } 23 | 24 | protected override int GetValueHashCode() 25 | { 26 | return HashCode.Combine(Name, Uri); 27 | } 28 | 29 | protected override bool ValueEquals(Picture other) 30 | { 31 | return Name.Equals(other.Name) && Uri.Equals(other.Uri); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Products/ValueObjects/ProductInfo.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using DDDMart.SharedKernel.Guards; 3 | 4 | namespace DDDMart.Catalogue.Core.Products.ValueObjects 5 | { 6 | public class ProductInfo : ValueObject 7 | { 8 | private ProductInfo(string name, string description) 9 | { 10 | Name = name; 11 | Description = description; 12 | } 13 | 14 | public static ProductInfo Create(string name, string description) 15 | { 16 | Guard.Against.NullOrEmpty(name, "Name"); 17 | Guard.Against.NullOrEmpty(description, "Description"); 18 | return new ProductInfo(name, description); 19 | } 20 | 21 | public string Name { get; private set; } 22 | public string Description { get; private set; } 23 | 24 | protected override int GetValueHashCode() 25 | { 26 | return HashCode.Combine(Name); 27 | } 28 | 29 | protected override bool ValueEquals(ProductInfo other) 30 | { 31 | return Name.Equals(other.Name); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/DomainEvents/ReviewCreatedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Catalogue.Core.Reviews.DomainEvents 5 | { 6 | public record ReviewCreatedDomainEvent(Guid Id, Customer Customer, Guid OrderId, Rating rating, Comment comment) : DomainEvent; 7 | } 8 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/DomainEvents/ReviewResponseCreatedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Catalogue.Core.Reviews.DomainEvents 5 | { 6 | public record ReviewResponseCreatedDomainEvent(Guid ReviewId, Guid ResponseId, Customer Customer, Comment comment) : DomainEvent; 7 | } 8 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/DomainEvents/ReviewUpdatedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Catalogue.Core.Reviews.DomainEvents 5 | { 6 | public record ReviewUpdatedDomainEvent(Guid Id, Customer Customer, Guid OrderId, Rating rating, Comment comment) : DomainEvent; 7 | } 8 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/Entities/Review.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.DomainEvents; 2 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 3 | using DDDMart.SharedKernel; 4 | using DDDMart.SharedKernel.Exceptions; 5 | 6 | namespace DDDMart.Catalogue.Core.Reviews.Entities 7 | { 8 | public class Review : AggregateRoot 9 | { 10 | private Review(Guid productId, Rating rating, Comment comment, 11 | Customer customer, Guid orderId) 12 | { 13 | ProductId = productId; 14 | Rating = rating; 15 | Comment = comment; 16 | Customer = customer; 17 | OrderId = orderId; 18 | } 19 | 20 | public static Review Create(Guid productId, Rating rating, Comment comment, 21 | Customer customer, Guid orderId) 22 | { 23 | var review = new Review(productId, rating, comment, customer, orderId); 24 | review.PublishCreated(); 25 | return review; 26 | } 27 | 28 | public Guid ProductId { get; private set; } 29 | public Rating Rating { get; private set; } 30 | public Comment Comment { get; private set; } 31 | public Customer Customer { get; private set; } 32 | public Guid OrderId { get; private set; } 33 | public const int ResponseDeadlineMonths = 6; 34 | 35 | private readonly List _responses = new List(); 36 | public IReadOnlyCollection Responses => _responses.AsReadOnly(); 37 | 38 | private void PublishCreated() 39 | { 40 | AddDomainEvent(new ReviewCreatedDomainEvent(Id, Customer, OrderId, Rating, Comment)); 41 | } 42 | 43 | public void Update(Rating rating, Comment comment) 44 | { 45 | Rating = rating; 46 | Comment = comment; 47 | AddDomainEvent(new ReviewUpdatedDomainEvent(Id, Customer, OrderId, Rating, Comment)); 48 | } 49 | 50 | public void Respond(Customer customer, Comment comment, DateTime responseDate) 51 | { 52 | CheckIfResponseDeadlinePassed(responseDate); 53 | var response = ReviewResponse.Create(customer, comment); 54 | _responses.Add(response); 55 | AddDomainEvent(new ReviewResponseCreatedDomainEvent(Id, response.Id, customer, comment)); 56 | } 57 | 58 | public void EditResponse(Guid responseId, Customer customer, Comment comment, DateTime responseDate) 59 | { 60 | var response = GetCustomerResponse(responseId, customer, responseDate); 61 | response.Update(comment); 62 | } 63 | 64 | public void DeleteResponse(Guid responseId, Customer customer, DateTime responseDate) 65 | { 66 | var response = GetCustomerResponse(responseId, customer, responseDate); 67 | _responses.Remove(response); 68 | } 69 | 70 | private ReviewResponse GetCustomerResponse(Guid responseId, Customer customer, DateTime responseDate) 71 | { 72 | CheckIfResponseDeadlinePassed(responseDate); 73 | var response = _responses.FirstOrDefault(e => e.Id == responseId); 74 | if (response == null) 75 | { 76 | throw new NotFoundException($"Response not found: {responseId}"); 77 | } 78 | if (!response.Customer.Equals(customer)) 79 | { 80 | throw new UnauthorizedAccessException(); 81 | } 82 | return response; 83 | } 84 | 85 | private void CheckIfResponseDeadlinePassed(DateTime responseDate) 86 | { 87 | if (responseDate > CreatedDate.AddMonths(ResponseDeadlineMonths)) 88 | { 89 | throw new DomainException($"Cannot respond to review that is over {ResponseDeadlineMonths} months old"); 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/Entities/ReviewResponse.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Catalogue.Core.Reviews.Entities 5 | { 6 | public class ReviewResponse : Entity 7 | { 8 | private ReviewResponse(Customer customer, Comment comment) 9 | { 10 | Customer = customer; 11 | Comment = comment; 12 | } 13 | 14 | internal static ReviewResponse Create(Customer customer, Comment comment) 15 | { 16 | return new ReviewResponse(customer, comment); 17 | } 18 | 19 | public Guid ReviewId { get; private set; } 20 | public Customer Customer { get; private set; } 21 | public Comment Comment { get; private set; } 22 | 23 | internal void Update(Comment comment) 24 | { 25 | Comment = comment; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/ValueObjects/Comment.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using DDDMart.SharedKernel.Guards; 3 | 4 | namespace DDDMart.Catalogue.Core.Reviews.ValueObjects 5 | { 6 | public class Comment : ValueObject 7 | { 8 | private Comment(string comment) 9 | { 10 | Value = comment; 11 | } 12 | 13 | public static Comment Create(string comment) 14 | { 15 | comment = (comment ?? string.Empty).Trim(); 16 | Guard.Against.NullOrEmpty(comment, "Comment"); 17 | Guard.Against.LengthGreaterThan(comment, 200, "Comment"); 18 | return new Comment(comment); 19 | } 20 | 21 | public string Value { get; private set; } 22 | 23 | protected override int GetValueHashCode() 24 | { 25 | return Value.GetHashCode(); 26 | } 27 | 28 | protected override bool ValueEquals(Comment other) 29 | { 30 | return Value.Equals(other.Value); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/ValueObjects/Customer.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Catalogue.Core.Reviews.ValueObjects 4 | { 5 | public class Customer : ValueObject 6 | { 7 | public Customer(Guid id, string name) 8 | { 9 | Id = id; 10 | Name = name; 11 | } 12 | 13 | public Guid Id { get; private set; } 14 | public string Name { get; private set; } 15 | 16 | protected override int GetValueHashCode() 17 | { 18 | return Id.GetHashCode(); 19 | } 20 | 21 | protected override bool ValueEquals(Customer other) 22 | { 23 | return Id.Equals(other.Id); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Core/Reviews/ValueObjects/Rating.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using DDDMart.SharedKernel.Guards; 3 | 4 | namespace DDDMart.Catalogue.Core.Reviews.ValueObjects 5 | { 6 | public class Rating : ValueObject 7 | { 8 | private Rating(int rating) 9 | { 10 | Value = rating; 11 | } 12 | 13 | public static Rating Create(int rating) 14 | { 15 | Guard.Against.LessThan(rating, 1, "Rating"); 16 | Guard.Against.GreaterThan(rating, 5, "Rating"); 17 | return new Rating(rating); 18 | } 19 | 20 | public int Value { get; private set; } 21 | 22 | protected override int GetValueHashCode() 23 | { 24 | return Value.GetHashCode(); 25 | } 26 | 27 | protected override bool ValueEquals(Rating other) 28 | { 29 | return Value.Equals(other.Value); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Infrastructure/AutofacModules/CatalogueInfrastructureModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Microsoft.Data.Sqlite; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace DDDMart.Catalogue.Infrastructure.AutofacModules 6 | { 7 | public class CatalogueInfrastructureModule : Module 8 | { 9 | protected override void Load(ContainerBuilder builder) 10 | { 11 | var connection = new SqliteConnection("DataSource=:memory:"); 12 | connection.Open(); 13 | var options = new DbContextOptionsBuilder() 14 | .UseSqlite(connection) 15 | .Options; 16 | 17 | builder.RegisterType() 18 | .AsSelf() 19 | .InstancePerRequest() 20 | .InstancePerLifetimeScope() 21 | .WithParameter(new NamedParameter("options", options)); 22 | 23 | builder.RegisterAssemblyTypes(ThisAssembly) 24 | .Where(e => e.Name.EndsWith("Repository")) 25 | .AsImplementedInterfaces() 26 | .InstancePerRequest() 27 | .InstancePerLifetimeScope(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Infrastructure/CatalogueContext.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core; 2 | using DDDMart.Catalogue.Core.Products.Entities; 3 | using DDDMart.Catalogue.Infrastructure.Configurations; 4 | using DDDMart.Infrastructure; 5 | using MediatR; 6 | using Microsoft.EntityFrameworkCore; 7 | 8 | namespace DDDMart.Catalogue.Infrastructure 9 | { 10 | public class CatalogueContext : DbContextBase 11 | { 12 | public CatalogueContext(DbContextOptions options, IMediator mediator, ICatalogueIntegrationEventMapper eventMapper) : base(options, mediator, eventMapper) 13 | { 14 | } 15 | 16 | public DbSet Products { get; set; } 17 | 18 | protected override void OnModelCreating(ModelBuilder modelBuilder) 19 | { 20 | base.OnModelCreating(modelBuilder); 21 | modelBuilder.HasDefaultSchema("catalogue"); 22 | modelBuilder.ApplyConfigurationsFromAssembly(typeof(ProductConfiguration).Assembly); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Infrastructure/Configurations/ProductConfiguration.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace DDDMart.Catalogue.Infrastructure.Configurations 6 | { 7 | internal class ProductConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.OwnsOne(e => e.Info, infoBuilder => 12 | { 13 | infoBuilder.HasIndex(e => e.Name).IsUnique(); 14 | }); 15 | 16 | builder.HasIndex(e => e.SicCode).IsUnique(); 17 | builder.OwnsOne(e => e.Picture); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Infrastructure/DDDMart.Catalogue.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/Catalogue/DDDMart.Catalogue.Infrastructure/Repositories/ProductsRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.Entities; 2 | using DDDMart.Catalogue.Core.Products.Repositories; 3 | using DDDMart.Infrastructure.Repositories; 4 | 5 | namespace DDDMart.Catalogue.Infrastructure.Repositories 6 | { 7 | public class ProductsRepository : Repository, IProductsRepository 8 | { 9 | public ProductsRepository(CatalogueContext context) : base(context) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/AutofacModules/EventBusModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using DDDMart.Application.EventBus; 3 | 4 | namespace DDDMart.Application.AutofacModules 5 | { 6 | public class EventBusModule : Module 7 | { 8 | protected override void Load(ContainerBuilder builder) 9 | { 10 | builder.RegisterType() 11 | .AsImplementedInterfaces() 12 | .SingleInstance(); 13 | 14 | builder.RegisterType() 15 | .AsImplementedInterfaces() 16 | .SingleInstance(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/DDDMart.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/EventBus/HandlerSubscription.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | 3 | namespace DDDMart.Application.EventBus 4 | { 5 | public sealed class HandlerSubscription : IEquatable 6 | { 7 | public HandlerSubscription(Type handlerType) 8 | { 9 | Type = handlerType; 10 | MethodInfo = handlerType.GetMethod("HandleAsync"); 11 | } 12 | 13 | public readonly Type Type; 14 | public readonly MethodInfo MethodInfo; 15 | 16 | public override bool Equals(object obj) 17 | { 18 | return Equals(obj as HandlerSubscription); 19 | } 20 | 21 | public bool Equals(HandlerSubscription other) 22 | { 23 | return other != null && Type.Equals(other.Type); 24 | } 25 | 26 | public override int GetHashCode() 27 | { 28 | return Type.GetHashCode(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/EventBus/IEventBus.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Application.EventBus 4 | { 5 | public interface IEventBus : IAsyncDisposable 6 | { 7 | Task PublishAsync(IntegrationEvent @event); 8 | void Subscribe() 9 | where TEvent : IntegrationEvent 10 | where THandler : IIntegrationEventHandler; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/EventBus/ISubscriptionContainer.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Application.EventBus 4 | { 5 | public interface ISubscriptionContainer 6 | { 7 | IReadOnlyList EventTypes { get; } 8 | Type GetEventType(string eventName); 9 | void Register() 10 | where TEvent : IntegrationEvent 11 | where THandler : IIntegrationEventHandler; 12 | Task HandleAsync(T @event) where T : IntegrationEvent; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/EventBus/InMemoryEventBus.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using Microsoft.Extensions.Logging; 3 | using Newtonsoft.Json; 4 | using System.Threading.Channels; 5 | 6 | namespace DDDMart.Application.EventBus 7 | { 8 | public class InMemoryEventBus : IEventBus 9 | { 10 | private readonly ILogger _logger; 11 | private readonly Channel _channel; 12 | private readonly object _lock = new object(); 13 | private bool _isProcessing = false; 14 | private Task _processingTask; 15 | private CancellationTokenSource _cancellationTokenSource; 16 | private readonly ISubscriptionContainer _subscriptionContainer; 17 | 18 | public InMemoryEventBus(ILogger logger, 19 | ISubscriptionContainer subscriptionContainer) 20 | { 21 | _logger = logger; 22 | _subscriptionContainer = subscriptionContainer; 23 | _channel = Channel.CreateUnbounded(); 24 | _cancellationTokenSource = new CancellationTokenSource(); 25 | } 26 | 27 | public async Task PublishAsync(IntegrationEvent @event) 28 | { 29 | _logger.LogInformation("Publishing {type}", @event.GetType().Name); 30 | var message = GetEventMessage(@event); 31 | await _channel.Writer.WriteAsync(message, CancellationToken.None); 32 | } 33 | 34 | private Message GetEventMessage(IntegrationEvent @event) 35 | { 36 | var body = JsonConvert.SerializeObject(@event); 37 | return new Message(body, @event.GetType().Name, DateTime.UtcNow); 38 | } 39 | 40 | public void Subscribe() 41 | where TEvent : IntegrationEvent 42 | where THandler : IIntegrationEventHandler 43 | { 44 | _logger.LogInformation("Subscribing to {type} with {handler}", typeof(TEvent).Name, typeof(THandler).Name); 45 | _subscriptionContainer.Register(); 46 | TryStartProcessing(); 47 | } 48 | 49 | private void TryStartProcessing() 50 | { 51 | bool startProcessing = false; 52 | lock (_lock) 53 | { 54 | if (!_isProcessing) 55 | { 56 | _isProcessing = true; 57 | startProcessing = true; 58 | } 59 | } 60 | if (startProcessing) 61 | { 62 | StartProcessing(_cancellationTokenSource.Token); 63 | } 64 | } 65 | 66 | private void StartProcessing(CancellationToken cancellationToken) 67 | { 68 | _processingTask = Task.Factory.StartNew(async () => 69 | { 70 | _logger.LogInformation("Listening for events"); 71 | while (await _channel.Reader.WaitToReadAsync(cancellationToken)) 72 | { 73 | while (_channel.Reader.TryRead(out Message message)) 74 | { 75 | _logger.LogInformation("Processing {type}", message.EventType); 76 | var @event = GetIntegrationEvent(message); 77 | await _subscriptionContainer.HandleAsync(@event); 78 | _logger.LogInformation("Completed processing {type}", @event.GetType().Name); 79 | } 80 | } 81 | }, TaskCreationOptions.LongRunning); 82 | } 83 | 84 | private IntegrationEvent GetIntegrationEvent(Message message) 85 | { 86 | var eventType = _subscriptionContainer.GetEventType(message.EventType); 87 | var @event = (IntegrationEvent)JsonConvert.DeserializeObject(message.Body, eventType); 88 | return @event; 89 | } 90 | 91 | public async ValueTask DisposeAsync() 92 | { 93 | if (_isProcessing) 94 | { 95 | _logger.LogInformation("Stopping event bus"); 96 | _cancellationTokenSource.Cancel(); 97 | await _processingTask; 98 | _isProcessing = false; 99 | } 100 | } 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/EventBus/Message.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.Application.EventBus 3 | { 4 | public sealed class Message 5 | { 6 | public Message(string body, string eventType, DateTime timestamp) 7 | { 8 | Body = body; 9 | EventType = eventType; 10 | Timestamp = timestamp; 11 | } 12 | 13 | public readonly string Body; 14 | public readonly string EventType; 15 | public readonly DateTime Timestamp; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/EventBus/SubscriptionContainer.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace DDDMart.Application.EventBus 6 | { 7 | public class SubscriptionContainer : ISubscriptionContainer 8 | { 9 | private readonly object _lock = new object(); 10 | private Dictionary> _subscriptions = new Dictionary>(); 11 | private readonly IServiceProvider _serviceProvider; 12 | private readonly ILogger _logger; 13 | private readonly Dictionary _eventTypes = new Dictionary(); 14 | 15 | public SubscriptionContainer(IServiceProvider serviceProvider, 16 | ILogger logger) 17 | { 18 | _serviceProvider = serviceProvider; 19 | _logger = logger; 20 | } 21 | 22 | public IReadOnlyList EventTypes => _eventTypes.Values.ToList(); 23 | 24 | public Type GetEventType(string eventName) 25 | { 26 | return _eventTypes[eventName]; 27 | } 28 | 29 | public void Register() 30 | where TEvent : IntegrationEvent 31 | where THandler : IIntegrationEventHandler 32 | { 33 | var eventType = typeof(TEvent); 34 | var handlerType = typeof(THandler); 35 | lock (_lock) 36 | { 37 | _eventTypes.Add(eventType.Name, eventType); 38 | if (!_subscriptions.TryGetValue(eventType, out List handlers)) 39 | { 40 | handlers = new List(); 41 | _subscriptions[eventType] = handlers; 42 | } 43 | handlers.Add(new HandlerSubscription(handlerType)); 44 | } 45 | } 46 | 47 | public async Task HandleAsync(T @event) where T : IntegrationEvent 48 | { 49 | var eventType = @event.GetType(); 50 | if (!_subscriptions.TryGetValue(eventType, out List handlerSubscriptions)) 51 | { 52 | throw new IndexOutOfRangeException($"No handlers registered for {eventType.Name}"); 53 | } 54 | 55 | foreach (var handlerSubscription in handlerSubscriptions) 56 | { 57 | _logger.LogInformation("Processing {handler}", handlerSubscription.Type.Name); 58 | using (var scope = _serviceProvider.CreateScope()) 59 | { 60 | try 61 | { 62 | var handler = scope.ServiceProvider.GetRequiredService(handlerSubscription.Type); 63 | await (Task)handlerSubscription.MethodInfo.Invoke(handler, new[] { @event }); 64 | } 65 | catch (Exception ex) 66 | { 67 | _logger.LogError(ex, $"Error handling integration event - {ex}", ex.ToString()); 68 | } 69 | } 70 | } 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/Factories/IntegrationEventFactory.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using DDDMart.SharedKernel.Outbox.Entities; 3 | using DDDMart.SharedKernel.Outbox.Factories; 4 | using Newtonsoft.Json; 5 | using System.Reflection; 6 | 7 | namespace DDDMart.Application.Factories 8 | { 9 | internal class IntegrationEventFactory : IIntegrationEventFactory 10 | { 11 | private readonly Dictionary _eventTypes; 12 | 13 | public IntegrationEventFactory(Assembly integrationEventAssembly) 14 | { 15 | var baseEventType = typeof(IntegrationEvent); 16 | _eventTypes = integrationEventAssembly 17 | .GetTypes() 18 | .Where(e => baseEventType.IsAssignableFrom(e)) 19 | .ToDictionary(e => e.Name); 20 | } 21 | 22 | public IntegrationEvent Create(OutboxIntegrationEvent integrationEvent) 23 | { 24 | var eventType = _eventTypes[integrationEvent.EventName]; 25 | var @event = JsonConvert.DeserializeObject(integrationEvent.Data, eventType); 26 | return (IntegrationEvent)@event; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/IIntegrationEventHandler.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Application 4 | { 5 | public interface IIntegrationEventHandler where T : IntegrationEvent 6 | { 7 | Task HandleAsync(T @event); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Application/IntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application.Factories; 2 | using DDDMart.SharedKernel; 3 | using DDDMart.SharedKernel.Outbox.Entities; 4 | using DDDMart.SharedKernel.Outbox.Factories; 5 | using DDDMart.SharedKernel.Outbox.Services; 6 | using Newtonsoft.Json; 7 | 8 | namespace DDDMart.Application 9 | { 10 | public abstract class IntegrationEventMapper : IIntegrationEventMapper 11 | { 12 | public IntegrationEventMapper() 13 | { 14 | Factory = new IntegrationEventFactory(this.GetType().Assembly); 15 | } 16 | 17 | public IIntegrationEventFactory Factory { get; } 18 | 19 | public List Map(IEnumerable domainEvents) 20 | { 21 | var integrationEvents = domainEvents.Select(e => MapDomainEvent(e)) 22 | .Where(e => e != null) 23 | .ToList(); 24 | 25 | return integrationEvents.Select(e => MapIntegrationEvent(e)).ToList(); 26 | } 27 | 28 | protected abstract IntegrationEvent MapDomainEvent(T domainEvent) where T : DomainEvent; 29 | 30 | private OutboxIntegrationEvent MapIntegrationEvent(IntegrationEvent integrationEvent) 31 | { 32 | var json = JsonConvert.SerializeObject(integrationEvent); 33 | return new OutboxIntegrationEvent(integrationEvent.GetType().Name, json); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Infrastructure/DDDMart.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Infrastructure/DbContextBase.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using DDDMart.SharedKernel.Outbox.Entities; 3 | using DDDMart.SharedKernel.Outbox.Services; 4 | using MediatR; 5 | using Microsoft.EntityFrameworkCore; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace DDDMart.Infrastructure 9 | { 10 | public abstract class DbContextBase : DbContext, IUnitOfWork where T : DbContextBase 11 | { 12 | private readonly IMediator _mediator; 13 | public readonly IIntegrationEventMapper EventMapper; 14 | 15 | protected DbContextBase(DbContextOptions options, 16 | IMediator mediator, 17 | IIntegrationEventMapper eventMapper) : base(options) 18 | { 19 | _mediator = mediator; 20 | EventMapper = eventMapper; 21 | } 22 | 23 | public DbSet OutboxIntegrationEvents { get; set; } 24 | 25 | public async Task CommitAsync(CancellationToken cancellationToken = default) 26 | { 27 | // Dispatch Domain Events collection. 28 | // Right BEFORE committing data (EF SaveChanges) into the DB will make a single transaction including 29 | // side effects from the domain event handlers which are using the same DbContext with "InstancePerLifetimeScope" or "scoped" lifetime 30 | // Integration Events will be stored in the IntegrationEventOutbox ready to be published later 31 | await _mediator.DispatchEventsAsync(this); 32 | 33 | // After executing this line all the changes (from the Command Handler and Domain Event Handlers) 34 | // performed through the DbContext will be committed 35 | await base.SaveChangesAsync(cancellationToken); 36 | 37 | return true; 38 | } 39 | 40 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 41 | { 42 | #if DEBUG 43 | // used to print SQL when debugging 44 | optionsBuilder.UseLoggerFactory(new LoggerFactory(new[] { new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider() })); 45 | #endif 46 | } 47 | 48 | protected override void OnModelCreating(ModelBuilder modelBuilder) 49 | { 50 | base.OnModelCreating(modelBuilder); 51 | modelBuilder.Ignore(); 52 | modelBuilder.Entity().Ignore(e => e.DomainEvents); 53 | modelBuilder.Entity().Property(q => q.Id).ValueGeneratedNever(); 54 | } 55 | } 56 | } -------------------------------------------------------------------------------- /src/Common/DDDMart.Infrastructure/Extensions/MediatorExtensions.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace MediatR 5 | { 6 | internal static class MediatorExtensions 7 | { 8 | public static async Task DispatchEventsAsync(this IMediator mediator, DbContextBase context) where T : DbContextBase 9 | { 10 | var aggregateRoots = context.ChangeTracker 11 | .Entries() 12 | .Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()) 13 | .Select(e => e.Entity) 14 | .ToList(); 15 | 16 | var domainEvents = aggregateRoots 17 | .SelectMany(x => x.DomainEvents) 18 | .ToList(); 19 | 20 | await mediator.DispatchDomainEventsAsync(domainEvents); 21 | await DispatchIntegrationEventsAsync(domainEvents, context); 22 | 23 | ClearDomainEvents(aggregateRoots); 24 | } 25 | 26 | private static async Task DispatchDomainEventsAsync(this IMediator mediator, List domainEvents) 27 | { 28 | foreach (var domainEvent in domainEvents) 29 | { 30 | await mediator.Publish(domainEvent); 31 | } 32 | } 33 | 34 | private static async Task DispatchIntegrationEventsAsync(IEnumerable domainEvents, DbContextBase context) where T : DbContextBase 35 | { 36 | var integrationEvents = context.EventMapper.Map(domainEvents); 37 | if (integrationEvents != null) 38 | { 39 | await context.OutboxIntegrationEvents.AddRangeAsync(integrationEvents); 40 | } 41 | } 42 | 43 | private static void ClearDomainEvents(List aggregateRoots) 44 | { 45 | aggregateRoots.ForEach(aggregate => aggregate.ClearDomainEvents()); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/Common/DDDMart.Infrastructure/Repositories/Repository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | using Microsoft.EntityFrameworkCore; 3 | 4 | namespace DDDMart.Infrastructure.Repositories 5 | { 6 | public abstract class Repository : IRepository where T : AggregateRoot where TContext : DbContextBase 7 | { 8 | private readonly DbContextBase _context; 9 | private readonly DbSet _entitySet; 10 | 11 | protected Repository(DbContextBase context) 12 | { 13 | _context = context; 14 | // EnsureCreated is being used here for testing purposes 15 | // and shouldn't be used in Production code 16 | _context.Database.EnsureCreated(); 17 | _entitySet = _context.Set(); 18 | } 19 | 20 | public IUnitOfWork UnitOfWork => _context; 21 | 22 | public IQueryable GetAll(bool noTracking = true) 23 | { 24 | var set = _entitySet; 25 | if (noTracking) 26 | { 27 | return set.AsNoTracking(); 28 | } 29 | return set; 30 | } 31 | 32 | public async Task GetByIdAsync(Guid id) 33 | { 34 | return await GetAll(false) 35 | .FirstOrDefaultAsync(e => e.Id == id); 36 | } 37 | 38 | public async Task InsertAsync(T entity) 39 | { 40 | await _entitySet.AddAsync(entity); 41 | } 42 | 43 | public void Delete(T entity) 44 | { 45 | _entitySet.Remove(entity); 46 | } 47 | 48 | public void Remove(IEnumerable entitiesToRemove) 49 | { 50 | _entitySet.RemoveRange(entitiesToRemove); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/AggregateRoot.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel 3 | { 4 | public abstract class AggregateRoot : Entity 5 | { 6 | protected AggregateRoot(Guid id) : base(id) 7 | { 8 | 9 | } 10 | 11 | protected AggregateRoot() 12 | { 13 | 14 | } 15 | 16 | private List _domainEvents; 17 | public IReadOnlyCollection DomainEvents => _domainEvents?.AsReadOnly(); 18 | 19 | protected void AddDomainEvent(DomainEvent eventItem) 20 | { 21 | _domainEvents = _domainEvents ?? new List(); 22 | _domainEvents.Add(eventItem); 23 | } 24 | 25 | public void ClearDomainEvents() 26 | { 27 | _domainEvents?.Clear(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/DDDMart.SharedKernel.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/DomainEvent.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace DDDMart.SharedKernel 4 | { 5 | public abstract record DomainEvent : INotification; 6 | } 7 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/DomainEventHandler.cs: -------------------------------------------------------------------------------- 1 | using MediatR; 2 | 3 | namespace DDDMart.SharedKernel 4 | { 5 | public interface IDomainEventHandler where T : DomainEvent 6 | { 7 | Task HandleAsync(T @event); 8 | } 9 | 10 | public abstract class DomainEventHandler : IDomainEventHandler, INotificationHandler where T : DomainEvent 11 | { 12 | public async Task Handle(T notification, CancellationToken cancellationToken) 13 | { 14 | await HandleAsync(notification); 15 | } 16 | 17 | public abstract Task HandleAsync(T @event); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Entity.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel 3 | { 4 | public abstract class Entity : IEqualityComparer, IEquatable 5 | { 6 | protected Entity(Guid id) 7 | { 8 | Id = id; 9 | CreatedDate = DateTime.UtcNow; 10 | } 11 | 12 | protected Entity() : this(Guid.NewGuid()) 13 | { 14 | 15 | } 16 | 17 | public Guid Id { get; protected set; } 18 | public DateTime CreatedDate { get; private set; } 19 | 20 | public override bool Equals(object obj) => this.Equals(obj as Entity); 21 | 22 | public bool Equals(Entity other) 23 | { 24 | if (other is null) 25 | { 26 | return false; 27 | } 28 | 29 | // Optimization for a common success case. 30 | if (Object.ReferenceEquals(this, other)) 31 | { 32 | return true; 33 | } 34 | 35 | // If run-time types are not exactly the same, return false. 36 | if (this.GetType() != other.GetType()) 37 | { 38 | return false; 39 | } 40 | 41 | // Return true if the fields match. 42 | // Note that the base class is not invoked because it is 43 | // System.Object, which defines Equals as reference equality. 44 | return Id.Equals(other.Id); 45 | } 46 | 47 | public bool Equals(Entity x, Entity y) 48 | { 49 | return x.Equals(y); 50 | } 51 | 52 | public override int GetHashCode() => (this.GetType().ToString() + Id.ToString()).GetHashCode(); 53 | 54 | public int GetHashCode(Entity obj) 55 | { 56 | return obj.GetHashCode(); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Exceptions/DomainException.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Exceptions 3 | { 4 | public class DomainException : Exception 5 | { 6 | public DomainException(string message, Exception ex) : base(message, ex) 7 | { 8 | 9 | } 10 | 11 | public DomainException(string message) : base(message) 12 | { 13 | 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Exceptions/NotFoundException.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Exceptions 3 | { 4 | public class NotFoundException : Exception 5 | { 6 | public NotFoundException() : base("Not found") 7 | { 8 | 9 | } 10 | 11 | public NotFoundException(string message) : base(message) 12 | { 13 | 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Guards/Guard.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Guards 3 | { 4 | /// 5 | /// Simple interface to provide a generic mechanism to build guard clause extension methods from. 6 | /// 7 | public interface IGuardClause 8 | { 9 | } 10 | 11 | /// 12 | /// An entry point to a set of Guard Clauses defined as extension methods on IGuardClause. 13 | /// 14 | public class Guard : IGuardClause 15 | { 16 | /// 17 | /// An entry point to a set of Guard Clauses. 18 | /// 19 | public static IGuardClause Against { get; } = new Guard(); 20 | 21 | private Guard() { } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Guards/GuardAgainstLengthExtensions.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Guards 3 | { 4 | public static partial class GuardClauseExtensions 5 | { 6 | public static string LengthGreaterThan(this IGuardClause guardClause, string input, int maxLength, string parameterName = "Value", string message = null) 7 | { 8 | if (input.Length > maxLength) 9 | { 10 | Error(message ?? $"'{parameterName}' length must be less than or equal to {maxLength}."); 11 | } 12 | return input; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Guards/GuardAgainstNullExtensions.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Guards 3 | { 4 | public static partial class GuardClauseExtensions 5 | { 6 | public static string NullOrEmpty(this IGuardClause guardClause, string input, string parameterName = "value", string message = null) 7 | { 8 | if (string.IsNullOrEmpty(input)) 9 | { 10 | Error(message ?? $"Required input '{parameterName}' is missing."); 11 | } 12 | return input; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Guards/GuardAgainstNumberExtensions.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Guards 3 | { 4 | public static partial class GuardClauseExtensions 5 | { 6 | public static decimal LessThan(this IGuardClause guardClause, decimal input, int minValue, string parameterName = "Amount", string message = null) 7 | { 8 | if (input < minValue) 9 | { 10 | Error(message ?? $"'{parameterName}' must be greater than or equal to {minValue}."); 11 | } 12 | return input; 13 | } 14 | 15 | public static decimal LessThanZero(this IGuardClause guardClause, decimal input, string parameterName = "Amount", string message = null) 16 | { 17 | return guardClause.LessThan(input, 0, parameterName, message); 18 | } 19 | 20 | public static decimal GreaterThan(this IGuardClause guardClause, decimal input, int maxValue, string parameterName = "Amount", string message = null) 21 | { 22 | if (input > maxValue) 23 | { 24 | Error(message ?? $"'{parameterName}' must be less than or equal to {maxValue}."); 25 | } 26 | return input; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Guards/GuardAgainstUrlExtensions.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Guards 3 | { 4 | public static partial class GuardClauseExtensions 5 | { 6 | public static string InvalidUrl(this IGuardClause guardClause, string url, string parameterName = "URL", string message = null) 7 | { 8 | try 9 | { 10 | _ = new Uri(url); 11 | } 12 | catch 13 | { 14 | Error(message ?? $"Must have a valid {parameterName}."); 15 | } 16 | return url; 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Guards/GuardClauseExtensions.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Exceptions; 2 | 3 | namespace DDDMart.SharedKernel.Guards 4 | { 5 | public static partial class GuardClauseExtensions 6 | { 7 | private static void Error(string message) 8 | { 9 | throw new DomainException(message); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/IRepository.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel 3 | { 4 | public interface IRepository where T : AggregateRoot 5 | { 6 | IUnitOfWork UnitOfWork { get; } 7 | IQueryable GetAll(bool noTracking = true); 8 | Task GetByIdAsync(Guid id); 9 | Task InsertAsync(T entity); 10 | void Delete(T entity); 11 | void Remove(IEnumerable entitiesToRemove); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/IUnitOfWork.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel 3 | { 4 | public interface IUnitOfWork : IDisposable 5 | { 6 | Task SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken)); 7 | Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken)); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/IntegrationEvent.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel 3 | { 4 | public abstract class IntegrationEvent 5 | { 6 | protected IntegrationEvent() : this(Guid.NewGuid()) 7 | { 8 | CreatedDate = DateTime.Now; 9 | } 10 | 11 | protected IntegrationEvent(Guid id) 12 | { 13 | Id = id; 14 | CreatedDate = DateTime.Now; 15 | } 16 | 17 | public readonly Guid Id; 18 | public readonly DateTime CreatedDate; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/IsExternalInit.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace System.Runtime.CompilerServices 3 | { 4 | using System.ComponentModel; 5 | /// 6 | /// Reserved to be used by the compiler for tracking metadata. 7 | /// This class should not be used by developers in source code. 8 | /// This is used to allow the use of records in C# 9.0 9 | /// 10 | [EditorBrowsable(EditorBrowsableState.Never)] 11 | public static class IsExternalInit 12 | { 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Outbox/Entities/OutboxIntegrationEvent.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel.Outbox.Entities 3 | { 4 | public class OutboxIntegrationEvent : AggregateRoot 5 | { 6 | public OutboxIntegrationEvent(string eventName, string data) 7 | { 8 | EventName = eventName; 9 | Data = data; 10 | } 11 | 12 | public string EventName { get; private set; } 13 | public string Data { get; private set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Outbox/Factories/IIntegrationEventFactory.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Outbox.Entities; 2 | 3 | namespace DDDMart.SharedKernel.Outbox.Factories 4 | { 5 | public interface IIntegrationEventFactory 6 | { 7 | IntegrationEvent Create(OutboxIntegrationEvent integrationEvent); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/Outbox/Services/IIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Outbox.Entities; 2 | using DDDMart.SharedKernel.Outbox.Factories; 3 | 4 | namespace DDDMart.SharedKernel.Outbox.Services 5 | { 6 | public interface IIntegrationEventMapper 7 | { 8 | public IIntegrationEventFactory Factory { get; } 9 | List Map(IEnumerable domainEvents); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/ValueObject.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.SharedKernel 3 | { 4 | public abstract class ValueObject where T : ValueObject 5 | { 6 | public override bool Equals(object obj) 7 | { 8 | var valueObject = obj as T; 9 | 10 | if (ReferenceEquals(valueObject, null)) 11 | return false; 12 | 13 | if (GetType() != obj.GetType()) 14 | return false; 15 | 16 | return ValueEquals(valueObject); 17 | } 18 | 19 | protected abstract bool ValueEquals(T other); 20 | 21 | public static bool operator ==(ValueObject a, ValueObject b) 22 | { 23 | if (ReferenceEquals(a, null) && ReferenceEquals(b, null)) 24 | return true; 25 | 26 | if (ReferenceEquals(a, null)) 27 | { 28 | return ReferenceEquals(b, null); 29 | } 30 | 31 | return a.Equals(b); 32 | } 33 | 34 | public static bool operator !=(ValueObject a, ValueObject b) 35 | { 36 | return !(a == b); 37 | } 38 | 39 | public override int GetHashCode() 40 | { 41 | return GetValueHashCode(); 42 | } 43 | 44 | protected abstract int GetValueHashCode(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Common/DDDMart.SharedKernel/ValueObjects/Address.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Guards; 2 | 3 | namespace DDDMart.SharedKernel.ValueObjects 4 | { 5 | public class Address : ValueObject
6 | { 7 | protected Address(string street, string city, string state, string country, string zipCode) 8 | { 9 | Street = street; 10 | City = city; 11 | State = state; 12 | Country = country; 13 | ZipCode = zipCode; 14 | } 15 | 16 | public string Street { get; private set; } 17 | public string City { get; private set; } 18 | public string State { get; private set; } 19 | public string Country { get; private set; } 20 | public string ZipCode { get; private set; } 21 | 22 | public virtual void Validate() 23 | { 24 | Guard.Against.NullOrEmpty(Street, "Street"); 25 | Guard.Against.NullOrEmpty(City, "City"); 26 | Guard.Against.NullOrEmpty(State, "State"); 27 | Guard.Against.NullOrEmpty(Country, "Country"); 28 | Guard.Against.NullOrEmpty(ZipCode, "Zip Code"); 29 | } 30 | 31 | protected override int GetValueHashCode() 32 | { 33 | return HashCode.Combine(Street, City, State, Country, ZipCode); 34 | } 35 | 36 | protected override bool ValueEquals(Address other) 37 | { 38 | return Street.Equals(other.Street) 39 | && City.Equals(other.City) 40 | && State.Equals(other.State) 41 | && Country.Equals(other.Country) 42 | && ZipCode.Equals(other.ZipCode); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/DDDMart/DDDMart.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /src/DDDMart/IntegrationEventPublisher.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application.EventBus; 2 | using DDDMart.Infrastructure; 3 | using DDDMart.SharedKernel.Outbox.Entities; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Hosting; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace DDDMart 9 | { 10 | public class IntegrationEventPublisher : BackgroundService where T : DbContextBase 11 | { 12 | private readonly IEventBus _eventBus; 13 | private readonly ILogger> _logger; 14 | private const int TIMEOUT_SECONDS = 1; 15 | private readonly IServiceProvider _serviceProvider; 16 | 17 | public IntegrationEventPublisher(IEventBus eventBus, 18 | ILogger> logger, 19 | IServiceProvider serviceProvider) 20 | { 21 | _eventBus = eventBus; 22 | _logger = logger; 23 | _serviceProvider = serviceProvider; 24 | } 25 | 26 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 27 | { 28 | _logger.LogInformation("Checking for integration events every {timeout}s", TIMEOUT_SECONDS); 29 | while (!stoppingToken.IsCancellationRequested) 30 | { 31 | await Task.Delay(TIMEOUT_SECONDS * 1000, stoppingToken); 32 | await PublishOutboxEventsAsync(); 33 | } 34 | } 35 | 36 | private async Task PublishOutboxEventsAsync() 37 | { 38 | using (var scope = _serviceProvider.CreateScope()) 39 | { 40 | var context = scope.ServiceProvider.GetRequiredService(); 41 | try 42 | { 43 | var integrationEvents = context.OutboxIntegrationEvents.AsQueryable().ToList(); 44 | 45 | if (integrationEvents.Any()) 46 | { 47 | _logger.LogInformation("Publishing {count} events from outbox", integrationEvents.Count); 48 | 49 | foreach (var integrationEvent in integrationEvents) 50 | { 51 | await PublishIntegrationEventAsync(integrationEvent, context); 52 | } 53 | context.OutboxIntegrationEvents.RemoveRange(integrationEvents); 54 | await context.CommitAsync(); 55 | } 56 | } 57 | catch (Exception ex) 58 | { 59 | _logger.LogError(ex, "Error publishing outbox events - {ex}", ex.ToString()); 60 | } 61 | } 62 | } 63 | 64 | private async Task PublishIntegrationEventAsync(OutboxIntegrationEvent integrationEvent, T context) 65 | { 66 | var @event = context.EventMapper.Factory.Create(integrationEvent); 67 | await _eventBus.PublishAsync(@event); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/DDDMart/IntegrationEventsService.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application.EventBus; 2 | using DDDMart.Ordering.Application.IntegrationEvents.Handlers; 3 | using DDDMart.Payments.Application.IntegrationEvents.Handlers; 4 | using Microsoft.Extensions.Hosting; 5 | 6 | namespace DDDMart 7 | { 8 | public class IntegrationEventsService : IHostedService 9 | { 10 | private readonly IEventBus _eventBus; 11 | 12 | public IntegrationEventsService(IEventBus eventBus) 13 | { 14 | _eventBus = eventBus; 15 | } 16 | 17 | public Task StartAsync(CancellationToken cancellationToken) 18 | { 19 | _eventBus.Subscribe(); 20 | _eventBus.Subscribe(); 21 | return Task.CompletedTask; 22 | } 23 | 24 | public async Task StopAsync(CancellationToken cancellationToken) 25 | { 26 | await _eventBus.DisposeAsync(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/DDDMart/OrderGenerator.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.Entities; 2 | using DDDMart.Catalogue.Core.Products.Repositories; 3 | using DDDMart.Catalogue.Core.Products.ValueObjects; 4 | using DDDMart.Ordering.Core.Baskets.Entities; 5 | using DDDMart.Ordering.Core.Baskets.Repositories; 6 | using DDDMart.Ordering.Core.Common.ValueObjects; 7 | using DDDMart.Ordering.Core.Orders.Entities; 8 | using DDDMart.Ordering.Core.Orders.Factories; 9 | using DDDMart.Ordering.Core.Orders.Repositories; 10 | using DDDMart.Payments.Core.Invoices.Repositories; 11 | using DDDMart.Payments.Core.PaymentMethods.Entities; 12 | using DDDMart.Payments.Core.PaymentMethods.Repositories; 13 | using DDDMart.Payments.Core.PaymentMethods.ValueObjects; 14 | using Microsoft.EntityFrameworkCore; 15 | using Microsoft.Extensions.Hosting; 16 | using Microsoft.Extensions.Logging; 17 | 18 | namespace DDDMart 19 | { 20 | public class OrderGenerator : BackgroundService 21 | { 22 | private readonly ILogger _logger; 23 | private readonly IProductsRepository _productsRepository; 24 | private readonly IBasketsRepository _basketsRepository; 25 | private readonly IOrdersRepository _ordersRepository; 26 | private readonly IPaymentMethodsRepository _paymentMethodsRepository; 27 | private readonly IInvoicesRepository _invoicesRepository; 28 | 29 | public OrderGenerator(ILogger logger, 30 | IProductsRepository productsRepository, 31 | IBasketsRepository basketsRepository, 32 | IOrdersRepository ordersRepository, 33 | IPaymentMethodsRepository paymentMethodsRepository, 34 | IInvoicesRepository invoicesRepository) 35 | { 36 | _logger = logger; 37 | _productsRepository = productsRepository; 38 | _basketsRepository = basketsRepository; 39 | _ordersRepository = ordersRepository; 40 | _paymentMethodsRepository = paymentMethodsRepository; 41 | _invoicesRepository = invoicesRepository; 42 | } 43 | 44 | protected override async Task ExecuteAsync(CancellationToken stoppingToken) 45 | { 46 | _logger.LogInformation("Generating orders"); 47 | await GenerateProductsAsync(); 48 | 49 | var customerId = Guid.NewGuid(); 50 | var basketId = await GenerateCustomerBasketAsync(customerId); 51 | await CheckoutAsync(basketId); 52 | var paymentMethodId = await SetupCustomerPaymentMethodAsync("Credit Card", PaymentType.CreditCard, customerId); 53 | var order = await _ordersRepository.GetAll(false).FirstOrDefaultAsync(e => e.BasketId == basketId); 54 | await CompleteOrderAsync(order, paymentMethodId); 55 | await PayInvoiceAsync(order.Id); 56 | } 57 | 58 | private async Task GenerateCustomerBasketAsync(Guid customerId) 59 | { 60 | _logger.LogInformation("Generating Customer Basket for: {id}", customerId); 61 | var products = await _productsRepository.GetAll().ToListAsync(); 62 | 63 | var basket = Basket.Create(customerId); 64 | AddProductToBasket(basket, products[0]); 65 | AddProductToBasket(basket, products[1]); 66 | AddProductToBasket(basket, products[2]); 67 | AddProductToBasket(basket, products[2]); 68 | AddProductToBasket(basket, products[3]); 69 | AddProductToBasket(basket, products[3]); 70 | AddProductToBasket(basket, products[3]); 71 | await _basketsRepository.InsertAsync(basket); 72 | await _basketsRepository.UnitOfWork.CommitAsync(); 73 | return basket.Id; 74 | } 75 | 76 | private async Task CheckoutAsync(Guid basketId) 77 | { 78 | _logger.LogInformation("Checking-out Customer Basket: {id}", basketId); 79 | var basket = await _basketsRepository.GetByIdAsync(basketId); 80 | basket.Checkout(); 81 | await _basketsRepository.UnitOfWork.CommitAsync(); 82 | } 83 | 84 | private async Task SetupCustomerPaymentMethodAsync(string name, PaymentType paymentType, Guid customerId) 85 | { 86 | _logger.LogInformation("Setting up {method} payment method for customer: {id}", paymentType.ToString(), customerId); 87 | var paymentMethod = PaymentMethod.Create(name, customerId, paymentType); 88 | await _paymentMethodsRepository.InsertAsync(paymentMethod); 89 | await _paymentMethodsRepository.UnitOfWork.CommitAsync(); 90 | return paymentMethod.Id; 91 | } 92 | 93 | private async Task CompleteOrderAsync(Order order, Guid paymentMethodId) 94 | { 95 | _logger.LogInformation("Setting up delivery address for {order}", order.Id); 96 | var addressFactory = new AddressFactory(); 97 | var shippingAddress = addressFactory.CreateShipping("4 Feather Lane", "City", "New York", "USA", "543534"); 98 | order.UpdateShippingAddress(shippingAddress); 99 | _logger.LogInformation("Setting up payment method for {order}", order.Id); 100 | var paymentAddress = addressFactory.CreatePayment("4 Feather Lane", "City", "New York", "USA", "543534"); 101 | order.UpdatePaymentMethod(paymentMethodId, paymentAddress); 102 | _logger.LogInformation("Submitting order {order}", order.Id); 103 | order.Submit(); 104 | await _ordersRepository.UnitOfWork.CommitAsync(); 105 | } 106 | 107 | private async Task PayInvoiceAsync(Guid orderId) 108 | { 109 | _logger.LogInformation("Searching for invoice for order {order}", orderId); 110 | var invoice = await _invoicesRepository.GetAll(false).FirstOrDefaultAsync(e => e.OrderId == orderId); 111 | while (invoice == null) 112 | { 113 | await Task.Delay(1000); 114 | invoice = await _invoicesRepository.GetAll(false).FirstOrDefaultAsync(e => e.OrderId == orderId); 115 | } 116 | _logger.LogInformation("Paying invoice {invoice}", invoice.Id); 117 | invoice.Pay(); 118 | await _invoicesRepository.UnitOfWork.CommitAsync(); 119 | } 120 | 121 | private void AddProductToBasket(Basket basket, Product product) 122 | { 123 | _logger.LogInformation("Adding {name} to basket", product.Info.Name); 124 | basket.AddItem(new OrderProduct(product.Id, product.Info.Name, product.Price)); 125 | } 126 | 127 | private async Task GenerateProductsAsync() 128 | { 129 | _logger.LogInformation("Generating Product Catalogue"); 130 | await _productsRepository.InsertAsync(Product.Create(ProductInfo.Create("SQL Server", "SQL Server relational database"), "0001", 100, Picture.Create("SQL Server", "https://ddmart.com/products/0001"))); 131 | await _productsRepository.InsertAsync(Product.Create(ProductInfo.Create("MongoDB Cluster", "MongoDB database cluster"), "0002", 200, Picture.Create("MongoDB Cluster", "https://ddmart.com/products/0002"))); 132 | await _productsRepository.InsertAsync(Product.Create(ProductInfo.Create("MongoDB Node", "MongoDB database node"), "0003", 80, Picture.Create("MongoDB Node", "https://ddmart.com/products/0003"))); 133 | await _productsRepository.InsertAsync(Product.Create(ProductInfo.Create("Web Server", "Web server"), "0004", 400, Picture.Create("Web Server", "https://ddmart.com/products/0004"))); 134 | await _productsRepository.UnitOfWork.CommitAsync(); 135 | } 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/DDDMart/Program.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Autofac.Extensions.DependencyInjection; 3 | using DDDMart; 4 | using DDDMart.Application.AutofacModules; 5 | using DDDMart.Catalogue.Application.AutofacModules; 6 | using DDDMart.Catalogue.Core.Products.Entities; 7 | using DDDMart.Catalogue.Infrastructure; 8 | using DDDMart.Catalogue.Infrastructure.AutofacModules; 9 | using DDDMart.Ordering.Application.AutofacModules; 10 | using DDDMart.Ordering.Core.AutofacModules; 11 | using DDDMart.Ordering.Infrastructure; 12 | using DDDMart.Ordering.Infrastructure.AutofacModules; 13 | using DDDMart.Payments.Application.AutofacModules; 14 | using DDDMart.Payments.Infrastructure; 15 | using DDDMart.Payments.Infrastructure.AutofacModules; 16 | using Microsoft.Extensions.DependencyInjection; 17 | using Microsoft.Extensions.Hosting; 18 | using Serilog; 19 | 20 | var host = Host.CreateDefaultBuilder() 21 | .UseServiceProviderFactory(new AutofacServiceProviderFactory()) 22 | .UseSerilog((hostContext, loggingBuilder) => 23 | { 24 | loggingBuilder.MinimumLevel.Information() 25 | .Enrich.FromLogContext() 26 | .WriteTo.Console(); 27 | }) 28 | .ConfigureServices(services => 29 | { 30 | services.AddMediatR(configuration => 31 | { 32 | configuration.RegisterServicesFromAssembly(typeof(Product).Assembly); 33 | }); 34 | services.AddHostedService(); 35 | services.AddHostedService(); 36 | services.AddHostedService>(); 37 | services.AddHostedService>(); 38 | services.AddHostedService>(); 39 | services.AddHostedService(); 40 | }) 41 | .ConfigureContainer(container => 42 | { 43 | container.RegisterModule(new CatalogueApplicationModule()); 44 | container.RegisterModule(new CatalogueInfrastructureModule()); 45 | container.RegisterModule(new OrderingApplicationModule()); 46 | container.RegisterModule(new OrderingCoreModule()); 47 | container.RegisterModule(new OrderingInfrastructureModule()); 48 | container.RegisterModule(new PaymentsApplicationModule()); 49 | container.RegisterModule(new PaymentsInfrastructureModule()); 50 | container.RegisterModule(new EventBusModule()); 51 | }) 52 | .Build(); 53 | 54 | await host.RunAsync(); -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/AutofacModules/OrderingApplicationModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using DDDMart.Ordering.Application.Services; 3 | 4 | namespace DDDMart.Ordering.Application.AutofacModules 5 | { 6 | public class OrderingApplicationModule : Module 7 | { 8 | protected override void Load(ContainerBuilder builder) 9 | { 10 | builder.RegisterType() 11 | .AsImplementedInterfaces() 12 | .SingleInstance(); 13 | 14 | builder.RegisterAssemblyTypes(ThisAssembly) 15 | .Where(e => e.Name.EndsWith("IntegrationEventHandler")); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/DDDMart.Ordering.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/IntegrationEvents/Handlers/InvoicePaidIntegrationEventHandler.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application; 2 | using DDDMart.Ordering.Core.Orders.Repositories; 3 | using Microsoft.Extensions.Logging; 4 | 5 | namespace DDDMart.Ordering.Application.IntegrationEvents.Handlers 6 | { 7 | public class InvoicePaidIntegrationEventHandler : IIntegrationEventHandler 8 | { 9 | private readonly ILogger _logger; 10 | private readonly IOrdersRepository _ordersRepository; 11 | 12 | public InvoicePaidIntegrationEventHandler(ILogger logger, 13 | IOrdersRepository ordersRepository) 14 | { 15 | _logger = logger; 16 | _ordersRepository = ordersRepository; 17 | } 18 | 19 | public async Task HandleAsync(InvoicePaidIntegrationEvent @event) 20 | { 21 | _logger.LogInformation("Setting order to paid {order}", @event.OrderId); 22 | var order = await _ordersRepository.GetByIdAsync(@event.OrderId); 23 | order.Pay(); 24 | _logger.LogInformation("Dispatching order {order}", @event.OrderId); 25 | order.Dispatch(); 26 | await _ordersRepository.UnitOfWork.CommitAsync(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/IntegrationEvents/InvoicePaidIntegrationEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Application.IntegrationEvents 4 | { 5 | public class InvoicePaidIntegrationEvent : IntegrationEvent 6 | { 7 | public InvoicePaidIntegrationEvent(Guid id, Guid customerId, Guid orderId, DateTime paidDate) :base(id) 8 | { 9 | CustomerId = customerId; 10 | OrderId = orderId; 11 | PaidDate = paidDate; 12 | } 13 | 14 | public readonly Guid CustomerId; 15 | public readonly Guid OrderId; 16 | public readonly DateTime PaidDate; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/IntegrationEvents/OrderCancelledIntegrationEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Application.IntegrationEvents 4 | { 5 | public class OrderCancelledIntegrationEvent : IntegrationEvent 6 | { 7 | public OrderCancelledIntegrationEvent(Guid id, Guid customerId) : base(id) 8 | { 9 | CustomerId = customerId; 10 | } 11 | 12 | public readonly Guid CustomerId; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/IntegrationEvents/OrderSubmittedIntegrationEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Application.IntegrationEvents 4 | { 5 | public class OrderSubmittedIntegrationEvent : IntegrationEvent 6 | { 7 | public OrderSubmittedIntegrationEvent(Guid id, Guid customerId, Guid paymentMethodId, string paymentStreet, 8 | string paymentCity, string paymentState, string paymentCountry, string paymentZipCode, decimal totalPrice) : base(id) 9 | { 10 | CustomerId = customerId; 11 | PaymentMethodId = paymentMethodId; 12 | PaymentStreet = paymentStreet; 13 | PaymentCity = paymentCity; 14 | PaymentState = paymentState; 15 | PaymentCountry = paymentCountry; 16 | PaymentZipCode = paymentZipCode; 17 | TotalPrice = totalPrice; 18 | } 19 | 20 | public readonly Guid CustomerId; 21 | public readonly Guid PaymentMethodId; 22 | public readonly string PaymentStreet; 23 | public readonly string PaymentCity; 24 | public readonly string PaymentState; 25 | public readonly string PaymentCountry; 26 | public readonly string PaymentZipCode; 27 | public readonly decimal TotalPrice; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Application/Services/OrderingIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application; 2 | using DDDMart.Ordering.Application.IntegrationEvents; 3 | using DDDMart.Ordering.Core; 4 | using DDDMart.Ordering.Core.Orders.DomainEvents; 5 | using DDDMart.SharedKernel; 6 | 7 | namespace DDDMart.Ordering.Application.Services 8 | { 9 | public class OrderingIntegrationEventMapper : IntegrationEventMapper, IOrderingIntegrationEventMapper 10 | { 11 | protected override IntegrationEvent MapDomainEvent(T domainEvent) 12 | { 13 | return domainEvent switch 14 | { 15 | OrderSubmittedDomainEvent @event => new OrderSubmittedIntegrationEvent(@event.Id, @event.CustomerId, @event.PaymentMethodId, @event.PaymentAddress.Street, @event.PaymentAddress.City, @event.PaymentAddress.State, @event.PaymentAddress.Country, @event.PaymentAddress.ZipCode, @event.TotalPrice), 16 | OrderCancelledDomainEvent @event => new OrderCancelledIntegrationEvent(@event.Id, @event.CustomerId), 17 | { } => null 18 | }; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/AutofacModules/OrderingCoreModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using MediatR; 3 | 4 | namespace DDDMart.Ordering.Core.AutofacModules 5 | { 6 | public class OrderingCoreModule : Module 7 | { 8 | protected override void Load(ContainerBuilder builder) 9 | { 10 | // Register the DomainEventHandler classes (they implement INotificationHandler<>) in assembly holding the Domain Events 11 | builder.RegisterAssemblyTypes(ThisAssembly) 12 | .AsClosedTypesOf(typeof(INotificationHandler<>)); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Baskets/DomainEvents/BasketCheckedOutDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Core.Baskets.DomainEvents 4 | { 5 | public record BasketCheckedOutDomainEvent(Guid BasketId, Guid CustomerId) : DomainEvent; 6 | } 7 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Baskets/Entities/Basket.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.DomainEvents; 2 | using DDDMart.Ordering.Core.Common.ValueObjects; 3 | using DDDMart.SharedKernel; 4 | using DDDMart.SharedKernel.Exceptions; 5 | 6 | namespace DDDMart.Ordering.Core.Baskets.Entities 7 | { 8 | public class Basket : AggregateRoot 9 | { 10 | private Basket(Guid customerId, bool checkedOut) 11 | { 12 | CustomerId = customerId; 13 | CheckedOut = checkedOut; 14 | } 15 | 16 | public static Basket Create(Guid customerId) 17 | { 18 | return new Basket(customerId, false); 19 | } 20 | 21 | public Guid CustomerId { get; private set; } 22 | public bool CheckedOut { get; private set; } 23 | 24 | private readonly List _items = new List(); 25 | public IReadOnlyCollection Items => _items.AsReadOnly(); 26 | 27 | public bool Empty => !_items.Any() || _items.All(e => e.Empty); 28 | 29 | public void AddItem(OrderProduct product) 30 | { 31 | var item = GetItem(product); 32 | if(item == null) 33 | { 34 | _items.Add(BasketItem.Create(product)); 35 | } 36 | else 37 | { 38 | item.Add(); 39 | } 40 | } 41 | 42 | public void RemoveItem(OrderProduct product) 43 | { 44 | var item = GetItem(product); 45 | if (item == null) 46 | { 47 | throw new DomainException($"No {product.Name} items in the basket to remove"); 48 | } 49 | else 50 | { 51 | item.Remove(); 52 | } 53 | } 54 | 55 | private BasketItem GetItem(OrderProduct product) 56 | { 57 | return _items.FirstOrDefault(e => e.Product == product); 58 | } 59 | 60 | public void Checkout() 61 | { 62 | if (Empty) 63 | { 64 | throw new DomainException("Cannot check-out as the basket is empty"); 65 | } 66 | if (CheckedOut) 67 | { 68 | throw new DomainException("The basket is already checked-out"); 69 | } 70 | CheckedOut = true; 71 | AddDomainEvent(new BasketCheckedOutDomainEvent(Id, CustomerId)); 72 | } 73 | 74 | public void Clear() 75 | { 76 | _items.Clear(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Baskets/Entities/BasketItem.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Common.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | using DDDMart.SharedKernel.Exceptions; 4 | 5 | namespace DDDMart.Ordering.Core.Baskets.Entities 6 | { 7 | public class BasketItem : Entity 8 | { 9 | private BasketItem(OrderProduct product, int quantity) 10 | { 11 | Product = product; 12 | Quantity = quantity; 13 | } 14 | 15 | private BasketItem() 16 | { 17 | 18 | } 19 | 20 | internal static BasketItem Create(OrderProduct product) 21 | { 22 | return new BasketItem(product, 1); 23 | } 24 | 25 | public OrderProduct Product { get; private set; } 26 | public int Quantity { get; private set; } 27 | public Guid BasketId { get; private set; } 28 | public decimal TotalPrice => Quantity * Product.Price; 29 | public bool Empty => Quantity == 0; 30 | 31 | public void Add() 32 | { 33 | Quantity++; 34 | } 35 | 36 | public void Remove() 37 | { 38 | if(Empty) 39 | { 40 | throw new DomainException($"Cannot remove product from basket as the quantity is 0 for {Product.Name}"); 41 | } 42 | Quantity--; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Baskets/Repositories/IBasketsRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.Entities; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Ordering.Core.Baskets.Repositories 5 | { 6 | public interface IBasketsRepository : IRepository 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Common/ValueObjects/OrderProduct.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Core.Common.ValueObjects 4 | { 5 | public class OrderProduct : ValueObject 6 | { 7 | public OrderProduct(Guid id, string name, decimal price) 8 | { 9 | Id = id; 10 | Name = name; 11 | Price = price; 12 | } 13 | 14 | public Guid Id { get; private set; } 15 | public string Name { get; private set; } 16 | public decimal Price { get; private set; } 17 | 18 | protected override int GetValueHashCode() 19 | { 20 | return Id.GetHashCode(); 21 | } 22 | 23 | protected override bool ValueEquals(OrderProduct other) 24 | { 25 | return Id.Equals(other.Id); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/DDDMart.Ordering.Core.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/IOrderingIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Outbox.Services; 2 | 3 | namespace DDDMart.Ordering.Core 4 | { 5 | public interface IOrderingIntegrationEventMapper : IIntegrationEventMapper 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/DomainEventHandlers/BasketCheckedOutDomainEventHandler.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.DomainEvents; 2 | using DDDMart.Ordering.Core.Baskets.Repositories; 3 | using DDDMart.Ordering.Core.Orders.Entities; 4 | using DDDMart.Ordering.Core.Orders.Repositories; 5 | using DDDMart.SharedKernel; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace DDDMart.Ordering.Core.Orders.DomainEventHandlers 9 | { 10 | public class BasketCheckedOutDomainEventHandler : DomainEventHandler 11 | { 12 | private readonly IBasketsRepository _basketsRepository; 13 | private readonly IOrdersRepository _ordersRepository; 14 | private readonly ILogger _logger; 15 | 16 | public BasketCheckedOutDomainEventHandler(IBasketsRepository basketsRepository, 17 | IOrdersRepository ordersRepository, 18 | ILogger logger) 19 | { 20 | _basketsRepository = basketsRepository; 21 | _ordersRepository = ordersRepository; 22 | _logger = logger; 23 | } 24 | 25 | public override async Task HandleAsync(BasketCheckedOutDomainEvent @event) 26 | { 27 | _logger.LogInformation("Creating order from basket {id}", @event.BasketId); 28 | var basket = await _basketsRepository.GetByIdAsync(@event.BasketId); 29 | var order = Order.FromBasket(basket); 30 | await _ordersRepository.InsertAsync(order); 31 | _logger.LogInformation("Created order {id}", order.Id); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/DomainEvents/OrderCancelledDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Core.Orders.DomainEvents 4 | { 5 | public record OrderCancelledDomainEvent(Guid Id, Guid CustomerId) : DomainEvent; 6 | } 7 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/DomainEvents/OrderDispatchedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Ordering.Core.Orders.DomainEvents 4 | { 5 | public record OrderDispatchedDomainEvent(Guid Id, Guid CustomerId, DateTime dispatchedDate) : DomainEvent; 6 | } 7 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/DomainEvents/OrderSubmittedDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Orders.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Ordering.Core.Orders.DomainEvents 5 | { 6 | public record OrderSubmittedDomainEvent(Guid Id, Guid CustomerId, Guid PaymentMethodId, PaymentAddress PaymentAddress, decimal TotalPrice) : DomainEvent; 7 | } 8 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/Entities/Order.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.Entities; 2 | using DDDMart.Ordering.Core.Orders.DomainEvents; 3 | using DDDMart.Ordering.Core.Orders.ValueObjects; 4 | using DDDMart.SharedKernel; 5 | using DDDMart.SharedKernel.Exceptions; 6 | 7 | namespace DDDMart.Ordering.Core.Orders.Entities 8 | { 9 | public class Order : AggregateRoot 10 | { 11 | private Order(Guid customerId, Guid basketId, OrderStatus orderStatus) 12 | { 13 | CustomerId = customerId; 14 | BasketId = basketId; 15 | Status = orderStatus; 16 | } 17 | 18 | private Order() 19 | { 20 | 21 | } 22 | 23 | public static Order FromBasket(Basket basket) 24 | { 25 | var order = new Order(basket.CustomerId, basket.Id, OrderStatus.Draft); 26 | foreach(var item in basket.Items.Where(e => !e.Empty)) 27 | { 28 | order.AddItemFromBasket(item); 29 | } 30 | return order; 31 | } 32 | 33 | public Guid CustomerId { get; private set; } 34 | public Guid BasketId { get; private set; } 35 | public OrderStatus Status { get; private set; } 36 | public ShippingAddress ShippingAddress { get; private set; } 37 | public Guid PaymentMethodId { get; private set; } 38 | public PaymentAddress PaymentAddress { get; private set; } 39 | public decimal TotalPrice => _items.Sum(e => e.TotalPrice); 40 | public bool Submitted => Status >= OrderStatus.Submitted; 41 | public DateTime? DispatchedDate { get; private set; } 42 | public bool Dispatched => DispatchedDate.HasValue; 43 | public DateTime? DeliveredDate { get; private set; } 44 | public bool Delivered => DeliveredDate.HasValue; 45 | public bool Cancelled => Status == OrderStatus.Cancelled; 46 | 47 | private readonly List _items = new List(); 48 | public IReadOnlyCollection Items => _items.AsReadOnly(); 49 | 50 | private void AddItemFromBasket(BasketItem item) 51 | { 52 | _items.Add(OrderItem.FromBasketItem(item)); 53 | } 54 | 55 | public void UpdateShippingAddress(ShippingAddress shippingAddress) 56 | { 57 | if(Status >= OrderStatus.Dispatched) 58 | { 59 | throw new DomainException("Cannot update Shipping Address, order has already been dispatched"); 60 | } 61 | if(Status < OrderStatus.ShippingAddressConfirmed) 62 | { 63 | Status = OrderStatus.ShippingAddressConfirmed; 64 | } 65 | ShippingAddress = shippingAddress; 66 | } 67 | 68 | public void UpdatePaymentMethod(Guid paymentMethodId, PaymentAddress paymentAddress) 69 | { 70 | if(Status < OrderStatus.ShippingAddressConfirmed) 71 | { 72 | throw new DomainException("Shipping Address must be selected before Payment Method"); 73 | } 74 | if (Status >= OrderStatus.Paid) 75 | { 76 | throw new DomainException("Cannot update Payment Method, payment has already been made"); 77 | } 78 | if (Status < OrderStatus.PaymentMethodConfirmed) 79 | { 80 | Status = OrderStatus.PaymentMethodConfirmed; 81 | } 82 | PaymentMethodId = paymentMethodId; 83 | PaymentAddress = paymentAddress; 84 | } 85 | 86 | public void Submit() 87 | { 88 | CheckIfCancelled(); 89 | if (Submitted) 90 | { 91 | throw new DomainException("Order has already been submitted"); 92 | } 93 | if(Status != OrderStatus.PaymentMethodConfirmed) 94 | { 95 | throw new DomainException("Payment Method and Delivery Address must be selected before submitting the order"); 96 | } 97 | Status = OrderStatus.Submitted; 98 | AddDomainEvent(new OrderSubmittedDomainEvent(Id, CustomerId, PaymentMethodId, PaymentAddress, TotalPrice)); 99 | } 100 | 101 | public void Pay() 102 | { 103 | CheckIfCancelled(); 104 | if (!Submitted) 105 | { 106 | throw new DomainException("Order has not been submitted"); 107 | } 108 | Status = OrderStatus.Paid; 109 | } 110 | 111 | public void Dispatch() 112 | { 113 | CheckIfCancelled(); 114 | if (Status != OrderStatus.Paid) 115 | { 116 | throw new DomainException("Order must be paid before dispatching"); 117 | } 118 | DispatchedDate = DateTime.UtcNow; 119 | Status = OrderStatus.Dispatched; 120 | AddDomainEvent(new OrderDispatchedDomainEvent(Id, CustomerId, DispatchedDate.Value)); 121 | } 122 | 123 | public void Deliver() 124 | { 125 | if (!Dispatched) 126 | { 127 | throw new DomainException("Order has not been dispatched yet"); 128 | } 129 | DeliveredDate = DateTime.UtcNow; 130 | Status= OrderStatus.Delivered; 131 | } 132 | 133 | public void Cancel() 134 | { 135 | Status = OrderStatus.Cancelled; 136 | AddDomainEvent(new OrderCancelledDomainEvent(Id, CustomerId)); 137 | } 138 | 139 | private void CheckIfCancelled() 140 | { 141 | if (Cancelled) 142 | { 143 | throw new DomainException("Order has been cancelled."); 144 | } 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/Entities/OrderItem.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.Entities; 2 | using DDDMart.Ordering.Core.Common.ValueObjects; 3 | using DDDMart.SharedKernel; 4 | 5 | namespace DDDMart.Ordering.Core.Orders.Entities 6 | { 7 | public class OrderItem : Entity 8 | { 9 | private OrderItem(OrderProduct product, int quantity) 10 | { 11 | Product = product; 12 | Quantity = quantity; 13 | } 14 | 15 | private OrderItem() 16 | { 17 | 18 | } 19 | 20 | internal static OrderItem FromBasketItem(BasketItem basketItem) 21 | { 22 | return new OrderItem(basketItem.Product, basketItem.Quantity); 23 | } 24 | 25 | public OrderProduct Product { get; private set; } 26 | public int Quantity { get; private set; } 27 | public Guid OrderId { get; private set; } 28 | public decimal TotalPrice => Quantity * Product.Price; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/Factories/AddressFactory.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Orders.ValueObjects; 2 | 3 | namespace DDDMart.Ordering.Core.Orders.Factories 4 | { 5 | public class AddressFactory 6 | { 7 | public ShippingAddress CreateShipping(string street, string city, string state, string country, string zipCode) 8 | { 9 | var address = new ShippingAddress(street, city, state, country, zipCode); 10 | address.Validate(); 11 | return address; 12 | } 13 | 14 | public PaymentAddress CreatePayment(string street, string city, string state, string country, string zipCode) 15 | { 16 | var address = new PaymentAddress(street, city, state, country, zipCode); 17 | address.Validate(); 18 | return address; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/Repositories/IOrdersRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Orders.Entities; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Ordering.Core.Orders.Repositories 5 | { 6 | public interface IOrdersRepository : IRepository 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/ValueObjects/OrderStatus.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.Ordering.Core.Orders.ValueObjects 3 | { 4 | public enum OrderStatus 5 | { 6 | Draft = 0, 7 | ShippingAddressConfirmed = 100, 8 | PaymentMethodConfirmed = 120, 9 | Submitted = 150, 10 | Paid = 200, 11 | Dispatched = 300, 12 | Delivered = 400, 13 | Cancelled = 900 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/ValueObjects/PaymentAddress.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.ValueObjects; 2 | 3 | namespace DDDMart.Ordering.Core.Orders.ValueObjects 4 | { 5 | public class PaymentAddress : Address 6 | { 7 | internal PaymentAddress(string street, string city, string state, string country, string zipCode) : base(street, city, state, country, zipCode) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Core/Orders/ValueObjects/ShippingAddress.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.ValueObjects; 2 | 3 | namespace DDDMart.Ordering.Core.Orders.ValueObjects 4 | { 5 | public class ShippingAddress : Address 6 | { 7 | internal ShippingAddress(string street, string city, string state, string country, string zipCode) : base(street, city, state, country, zipCode) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/AutofacModules/OrderingInfrastructureModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Microsoft.Data.Sqlite; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace DDDMart.Ordering.Infrastructure.AutofacModules 6 | { 7 | public class OrderingInfrastructureModule : Module 8 | { 9 | protected override void Load(ContainerBuilder builder) 10 | { 11 | var connection = new SqliteConnection("DataSource=:memory:"); 12 | connection.Open(); 13 | var options = new DbContextOptionsBuilder() 14 | .UseSqlite(connection) 15 | .Options; 16 | 17 | builder.RegisterType() 18 | .AsSelf() 19 | .InstancePerRequest() 20 | .InstancePerLifetimeScope() 21 | .WithParameter(new NamedParameter("options", options)); 22 | 23 | builder.RegisterAssemblyTypes(ThisAssembly) 24 | .Where(e => e.Name.EndsWith("Repository")) 25 | .AsImplementedInterfaces() 26 | .InstancePerRequest() 27 | .InstancePerLifetimeScope(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/Configurations/BasketConfiguration.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace DDDMart.Ordering.Infrastructure.Configurations 6 | { 7 | internal class BasketConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasMany(e => e.Items) 12 | .WithOne() 13 | .HasForeignKey(e => e.BasketId); 14 | 15 | builder.HasIndex(e => e.CustomerId); 16 | } 17 | } 18 | 19 | internal class BasketItemConfiguration : IEntityTypeConfiguration 20 | { 21 | public void Configure(EntityTypeBuilder builder) 22 | { 23 | builder.OwnsOne(e => e.Product); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/Configurations/OrderConfiguration.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Orders.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace DDDMart.Ordering.Infrastructure.Configurations 6 | { 7 | internal class OrderConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.OwnsOne(e => e.ShippingAddress); 12 | builder.OwnsOne(e => e.PaymentAddress); 13 | 14 | builder.HasIndex(e => e.CustomerId); 15 | builder.HasIndex(e => e.BasketId).IsUnique(); 16 | 17 | builder.HasMany(e => e.Items) 18 | .WithOne() 19 | .HasForeignKey(e => e.OrderId); 20 | } 21 | } 22 | 23 | internal class OrderItemConfiguration : IEntityTypeConfiguration 24 | { 25 | public void Configure(EntityTypeBuilder builder) 26 | { 27 | builder.OwnsOne(e => e.Product); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/DDDMart.Ordering.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/OrderingContext.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure; 2 | using DDDMart.Ordering.Core; 3 | using DDDMart.Ordering.Core.Baskets.Entities; 4 | using DDDMart.Ordering.Core.Orders.Entities; 5 | using DDDMart.Ordering.Infrastructure.Configurations; 6 | using MediatR; 7 | using Microsoft.EntityFrameworkCore; 8 | 9 | namespace DDDMart.Ordering.Infrastructure 10 | { 11 | public class OrderingContext : DbContextBase 12 | { 13 | public OrderingContext(DbContextOptions options, IMediator mediator, IOrderingIntegrationEventMapper eventMapper) : base(options, mediator, eventMapper) 14 | { 15 | } 16 | 17 | public DbSet Baskets { get; set; } 18 | public DbSet Orders { get; set; } 19 | 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | base.OnModelCreating(modelBuilder); 23 | modelBuilder.HasDefaultSchema("baskets"); 24 | modelBuilder.ApplyConfigurationsFromAssembly(typeof(BasketConfiguration).Assembly); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/Repositories/BasketsRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure.Repositories; 2 | using DDDMart.Ordering.Core.Baskets.Entities; 3 | using DDDMart.Ordering.Core.Baskets.Repositories; 4 | 5 | namespace DDDMart.Ordering.Infrastructure.Repositories 6 | { 7 | public class BasketsRepository : Repository, IBasketsRepository 8 | { 9 | public BasketsRepository(OrderingContext context) : base(context) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Ordering/DDDMart.Ordering.Infrastructure/Repositories/OrdersRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure.Repositories; 2 | using DDDMart.Ordering.Core.Orders.Entities; 3 | using DDDMart.Ordering.Core.Orders.Repositories; 4 | 5 | namespace DDDMart.Ordering.Infrastructure.Repositories 6 | { 7 | public class OrdersRepository : Repository, IOrdersRepository 8 | { 9 | public OrdersRepository(OrderingContext context) : base(context) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Application/AutofacModules/PaymentsApplicationModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using DDDMart.Payments.Application.Services; 3 | 4 | namespace DDDMart.Payments.Application.AutofacModules 5 | { 6 | public class PaymentsApplicationModule : Module 7 | { 8 | protected override void Load(ContainerBuilder builder) 9 | { 10 | builder.RegisterType() 11 | .AsImplementedInterfaces() 12 | .SingleInstance(); 13 | 14 | builder.RegisterAssemblyTypes(ThisAssembly) 15 | .Where(e => e.Name.EndsWith("IntegrationEventHandler")); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Application/DDDMart.Payments.Application.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Application/IntegrationEvents/Handlers/OrderSubmittedIntegrationEventHandler.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application; 2 | using DDDMart.Payments.Core.Invoices.Entities; 3 | using DDDMart.Payments.Core.Invoices.Repositories; 4 | using DDDMart.Payments.Core.Invoices.ValueObjects; 5 | using Microsoft.Extensions.Logging; 6 | 7 | namespace DDDMart.Payments.Application.IntegrationEvents.Handlers 8 | { 9 | public class OrderSubmittedIntegrationEventHandler : IIntegrationEventHandler 10 | { 11 | private readonly ILogger _logger; 12 | private readonly IInvoicesRepository _invoicesRepository; 13 | 14 | public OrderSubmittedIntegrationEventHandler(ILogger logger, 15 | IInvoicesRepository invoicesRepository) 16 | { 17 | _logger = logger; 18 | _invoicesRepository = invoicesRepository; 19 | } 20 | 21 | public async Task HandleAsync(OrderSubmittedIntegrationEvent @event) 22 | { 23 | _logger.LogInformation("Generating invoice for order {order}", @event.Id); 24 | var invoice = Invoice.Generate(@event.CustomerId, @event.Id, @event.PaymentMethodId, InvoiceAddress.Create(@event.PaymentStreet, @event.PaymentCity, @event.PaymentState, @event.PaymentCountry, @event.PaymentZipCode), @event.TotalPrice); 25 | await _invoicesRepository.InsertAsync(invoice); 26 | await _invoicesRepository.UnitOfWork.CommitAsync(); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Application/IntegrationEvents/InvoicePaidIntegrationEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Payments.Application.IntegrationEvents 4 | { 5 | public class InvoicePaidIntegrationEvent : IntegrationEvent 6 | { 7 | public InvoicePaidIntegrationEvent(Guid id, Guid customerId, Guid orderId, DateTime paidDate) :base(id) 8 | { 9 | CustomerId = customerId; 10 | OrderId = orderId; 11 | PaidDate = paidDate; 12 | } 13 | 14 | public readonly Guid CustomerId; 15 | public readonly Guid OrderId; 16 | public readonly DateTime PaidDate; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Application/IntegrationEvents/OrderSubmittedIntegrationEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Payments.Application.IntegrationEvents 4 | { 5 | public class OrderSubmittedIntegrationEvent : IntegrationEvent 6 | { 7 | public OrderSubmittedIntegrationEvent(Guid id, Guid customerId, Guid paymentMethodId, string paymentStreet, 8 | string paymentCity, string paymentState, string paymentCountry, string paymentZipCode, decimal totalPrice) : base(id) 9 | { 10 | CustomerId = customerId; 11 | PaymentMethodId = paymentMethodId; 12 | PaymentStreet = paymentStreet; 13 | PaymentCity = paymentCity; 14 | PaymentState = paymentState; 15 | PaymentCountry = paymentCountry; 16 | PaymentZipCode = paymentZipCode; 17 | TotalPrice = totalPrice; 18 | } 19 | 20 | public readonly Guid CustomerId; 21 | public readonly Guid PaymentMethodId; 22 | public readonly string PaymentStreet; 23 | public readonly string PaymentCity; 24 | public readonly string PaymentState; 25 | public readonly string PaymentCountry; 26 | public readonly string PaymentZipCode; 27 | public readonly decimal TotalPrice; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Application/Services/PaymentsIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Application; 2 | using DDDMart.Payments.Application.IntegrationEvents; 3 | using DDDMart.Payments.Core; 4 | using DDDMart.Payments.Core.Invoices.DomainEvents; 5 | using DDDMart.SharedKernel; 6 | 7 | namespace DDDMart.Payments.Application.Services 8 | { 9 | public class PaymentsIntegrationEventMapper : IntegrationEventMapper, IPaymentsIntegrationEventMapper 10 | { 11 | protected override IntegrationEvent MapDomainEvent(T domainEvent) 12 | { 13 | return domainEvent switch 14 | { 15 | InvoicePaidDomainEvent @event => new InvoicePaidIntegrationEvent(@event.Id, @event.CustomerId, @event.OrderId, @event.PaidDate), 16 | { } => null 17 | }; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/DDDMart.Payments.Core.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/IPaymentsIntegrationEventMapper.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.Outbox.Services; 2 | 3 | namespace DDDMart.Payments.Core 4 | { 5 | public interface IPaymentsIntegrationEventMapper : IIntegrationEventMapper 6 | { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/Invoices/DomainEvents/InvoicePaidDomainEvent.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel; 2 | 3 | namespace DDDMart.Payments.Core.Invoices.DomainEvents 4 | { 5 | public record InvoicePaidDomainEvent(Guid Id, DateTime PaidDate, Guid OrderId, Guid CustomerId) : DomainEvent; 6 | } 7 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/Invoices/Entities/Invoice.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.Invoices.DomainEvents; 2 | using DDDMart.Payments.Core.Invoices.ValueObjects; 3 | using DDDMart.SharedKernel; 4 | using DDDMart.SharedKernel.Exceptions; 5 | 6 | namespace DDDMart.Payments.Core.Invoices.Entities 7 | { 8 | public class Invoice : AggregateRoot 9 | { 10 | private Invoice(Guid customerId, Guid orderId, Guid paymentMethodId, InvoiceAddress invoiceAddress, decimal amount, InvoiceStatus status, DateTime sentDate, DateTime? paidDate) 11 | { 12 | CustomerId = customerId; 13 | OrderId = orderId; 14 | PaymentMethodId = paymentMethodId; 15 | Amount = amount; 16 | Status = status; 17 | SentDate = sentDate; 18 | PaidDate = paidDate; 19 | Address = invoiceAddress; 20 | } 21 | 22 | private Invoice() 23 | { 24 | 25 | } 26 | 27 | public static Invoice Generate(Guid customerId, Guid orderId, Guid paymentMethodId, InvoiceAddress invoiceAddress, decimal amount) 28 | { 29 | return new Invoice(customerId, orderId, paymentMethodId, invoiceAddress, amount, InvoiceStatus.NotPaid, DateTime.UtcNow, null); 30 | } 31 | 32 | public Guid CustomerId { get; private set; } 33 | public Guid OrderId { get; private set; } 34 | public InvoiceAddress Address { get; private set; } 35 | public Guid PaymentMethodId { get; private set; } 36 | public decimal Amount { get; private set; } 37 | public InvoiceStatus Status { get; private set; } 38 | public DateTime SentDate { get; private set; } 39 | public DateTime? PaidDate { get; private set; } 40 | public bool Paid => PaidDate.HasValue; 41 | 42 | public void Pay() 43 | { 44 | if (Paid) 45 | { 46 | throw new DomainException($"Invoice has already been paid on {PaidDate.Value}"); 47 | } 48 | Status = InvoiceStatus.Paid; 49 | PaidDate = DateTime.UtcNow; 50 | AddDomainEvent(new InvoicePaidDomainEvent(Id, PaidDate.Value, OrderId, CustomerId)); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/Invoices/Repositories/IInvoicesRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.Invoices.Entities; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Payments.Core.Invoices.Repositories 5 | { 6 | public interface IInvoicesRepository : IRepository 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/Invoices/ValueObjects/InvoiceAddress.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.SharedKernel.ValueObjects; 2 | 3 | namespace DDDMart.Payments.Core.Invoices.ValueObjects 4 | { 5 | public class InvoiceAddress : Address 6 | { 7 | protected InvoiceAddress(string street, string city, string state, string country, string zipCode) : base(street, city, state, country, zipCode) 8 | { 9 | } 10 | 11 | public static InvoiceAddress Create(string street, string city, string state, string country, string zipCode) 12 | { 13 | var address = new InvoiceAddress(street, city, state, country, zipCode); 14 | address.Validate(); 15 | return address; 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/Invoices/ValueObjects/InvoiceStatus.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.Payments.Core.Invoices.ValueObjects 3 | { 4 | public enum InvoiceStatus 5 | { 6 | NotPaid, 7 | Paid 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/PaymentMethods/Entities/PaymentMethod.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.PaymentMethods.ValueObjects; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Payments.Core.PaymentMethods.Entities 5 | { 6 | public class PaymentMethod : AggregateRoot 7 | { 8 | private PaymentMethod(string name, Guid customerId, PaymentType paymentType, PaymentMethodStatus status) 9 | { 10 | Name = name; 11 | CustomerId = customerId; 12 | PaymentType = paymentType; 13 | Status = status; 14 | } 15 | 16 | public static PaymentMethod Create(string name, Guid customerId, PaymentType paymentType) 17 | { 18 | return new PaymentMethod(name, customerId, paymentType, PaymentMethodStatus.Valid); 19 | } 20 | 21 | public string Name { get; private set; } 22 | public Guid CustomerId { get; private set; } 23 | public PaymentType PaymentType { get; private set; } 24 | public PaymentMethodStatus Status { get; private set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/PaymentMethods/Repositories/IPaymentMethodsRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.PaymentMethods.Entities; 2 | using DDDMart.SharedKernel; 3 | 4 | namespace DDDMart.Payments.Core.PaymentMethods.Repositories 5 | { 6 | public interface IPaymentMethodsRepository : IRepository 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/PaymentMethods/ValueObjects/PaymentMethodStatus.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.Payments.Core.PaymentMethods.ValueObjects 3 | { 4 | public enum PaymentMethodStatus 5 | { 6 | Valid, 7 | Expired 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Core/PaymentMethods/ValueObjects/PaymentType.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.Payments.Core.PaymentMethods.ValueObjects 3 | { 4 | public enum PaymentType 5 | { 6 | CreditCard, 7 | DebitCard, 8 | Paypal 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/AutofacModules/PaymentsInfrastructureModule.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using Microsoft.Data.Sqlite; 3 | using Microsoft.EntityFrameworkCore; 4 | 5 | namespace DDDMart.Payments.Infrastructure.AutofacModules 6 | { 7 | public class PaymentsInfrastructureModule : Module 8 | { 9 | protected override void Load(ContainerBuilder builder) 10 | { 11 | var connection = new SqliteConnection("DataSource=:memory:"); 12 | connection.Open(); 13 | var options = new DbContextOptionsBuilder() 14 | .UseSqlite(connection) 15 | .Options; 16 | 17 | builder.RegisterType() 18 | .AsSelf() 19 | .InstancePerRequest() 20 | .InstancePerLifetimeScope() 21 | .WithParameter(new NamedParameter("options", options)); 22 | 23 | builder.RegisterAssemblyTypes(ThisAssembly) 24 | .Where(e => e.Name.EndsWith("Repository")) 25 | .AsImplementedInterfaces() 26 | .InstancePerRequest() 27 | .InstancePerLifetimeScope(); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/Configurations/InvoiceConfiguration.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.Invoices.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace DDDMart.Payments.Infrastructure.Configurations 6 | { 7 | internal class InvoiceConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.OwnsOne(e => e.Address); 12 | 13 | builder.HasIndex(e => e.CustomerId); 14 | builder.HasIndex(e => e.OrderId).IsUnique(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/Configurations/PaymentMethodConfiguration.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.PaymentMethods.Entities; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.EntityFrameworkCore.Metadata.Builders; 4 | 5 | namespace DDDMart.Payments.Infrastructure.Configurations 6 | { 7 | internal class PaymentMethodConfiguration : IEntityTypeConfiguration 8 | { 9 | public void Configure(EntityTypeBuilder builder) 10 | { 11 | builder.HasIndex(e => new { e.CustomerId, e.Name }).IsUnique(); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/DDDMart.Payments.Infrastructure.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/PaymentsContext.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure; 2 | using DDDMart.Payments.Core; 3 | using DDDMart.Payments.Core.Invoices.Entities; 4 | using DDDMart.Payments.Core.PaymentMethods.Entities; 5 | using DDDMart.Payments.Infrastructure.Configurations; 6 | using MediatR; 7 | using Microsoft.EntityFrameworkCore; 8 | 9 | namespace DDDMart.Payments.Infrastructure 10 | { 11 | public class PaymentsContext : DbContextBase 12 | { 13 | public PaymentsContext(DbContextOptions options, IMediator mediator, IPaymentsIntegrationEventMapper eventMapper) : base(options, mediator, eventMapper) 14 | { 15 | } 16 | 17 | public DbSet Invoices { get; set; } 18 | public DbSet PaymentMethods { get; set; } 19 | 20 | protected override void OnModelCreating(ModelBuilder modelBuilder) 21 | { 22 | base.OnModelCreating(modelBuilder); 23 | modelBuilder.HasDefaultSchema("payments"); 24 | modelBuilder.ApplyConfigurationsFromAssembly(typeof(InvoiceConfiguration).Assembly); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/Repositories/InvoicesRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure.Repositories; 2 | using DDDMart.Payments.Core.Invoices.Entities; 3 | using DDDMart.Payments.Core.Invoices.Repositories; 4 | 5 | namespace DDDMart.Payments.Infrastructure.Repositories 6 | { 7 | public class InvoicesRepository : Repository, IInvoicesRepository 8 | { 9 | public InvoicesRepository(PaymentsContext context) : base(context) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/Payments/DDDMart.Payments.Infrastructure/Repositories/PaymentMethodsRepository.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Infrastructure.Repositories; 2 | using DDDMart.Payments.Core.PaymentMethods.Entities; 3 | using DDDMart.Payments.Core.PaymentMethods.Repositories; 4 | 5 | namespace DDDMart.Payments.Infrastructure.Repositories 6 | { 7 | public class PaymentMethodsRepository : Repository, IPaymentMethodsRepository 8 | { 9 | public PaymentMethodsRepository(PaymentsContext context) : base(context) 10 | { 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/Builders/ProductBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.Entities; 2 | using DDDMart.Catalogue.Core.Products.ValueObjects; 3 | using System.Reflection; 4 | 5 | namespace DDDMart.Catalogue.Core.Tests.Builders 6 | { 7 | public class ProductBuilder 8 | { 9 | private Guid? _id; 10 | private string _name = "SQL Server"; 11 | private string _description = "SQL Server relational database"; 12 | private string _sicCode = "1234"; 13 | private decimal _price = 100; 14 | 15 | public Product Build() 16 | { 17 | var product = Product.Create(ProductInfo.Create(_name, _description), _sicCode, _price, Picture.Create("Test", "https://test.com")); 18 | if (_id.HasValue) 19 | { 20 | product.GetType().GetProperty(nameof(product.Id), BindingFlags.Public | BindingFlags.Instance).SetValue(product, _id.Value, null); 21 | } 22 | return product; 23 | } 24 | 25 | public ProductBuilder WithId(Guid id) 26 | { 27 | _id = id; 28 | return this; 29 | } 30 | 31 | public ProductBuilder WithName(string name) 32 | { 33 | _name = name; 34 | return this; 35 | } 36 | 37 | public ProductBuilder WithPrice(decimal price) 38 | { 39 | _price = price; 40 | return this; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/Builders/ReviewBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.Entities; 2 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 3 | 4 | namespace DDDMart.Catalogue.Core.Tests.Builders 5 | { 6 | public class ReviewBuilder 7 | { 8 | private Guid _productId = Guid.NewGuid(); 9 | private Guid _orderId = Guid.NewGuid(); 10 | private Guid _customerId = Guid.NewGuid(); 11 | private string _customerName = "Test User"; 12 | private int _rating = 4; 13 | private string _comment = "This is a test comment."; 14 | 15 | public Review Build() 16 | { 17 | var rating = Rating.Create(_rating); 18 | var comment = Comment.Create(_comment); 19 | var customer = new Customer(_customerId, _customerName); 20 | var review = Review.Create(_productId, rating, comment, customer, _orderId); 21 | return review; 22 | } 23 | 24 | public ReviewBuilder WithRating(int rating) 25 | { 26 | _rating = rating; 27 | return this; 28 | } 29 | 30 | public ReviewBuilder WithComment(string comment) 31 | { 32 | _comment = comment; 33 | return this; 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/DDDMart.Catalogue.Core.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | global using FluentAssertions; 3 | global using Moq; -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/Products/Entities/ProductTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Tests.Builders; 2 | using DDDMart.SharedKernel.Exceptions; 3 | 4 | namespace DDDMart.Catalogue.Core.Tests.Entities 5 | { 6 | [TestClass] 7 | public class ProductTests 8 | { 9 | [TestMethod] 10 | public void GivenProduct_WhenSameId_ThenEquals() 11 | { 12 | var id = Guid.NewGuid(); 13 | var product1 = new ProductBuilder().WithId(id).Build(); 14 | var product2 = new ProductBuilder().WithId(id).Build(); 15 | product1.Should().Be(product2); 16 | product1.GetHashCode().Should().Be(product2.GetHashCode()); 17 | } 18 | 19 | [TestMethod] 20 | public void GivenProduct_WhenCreate_ThenCreate() 21 | { 22 | var name = "Test"; 23 | var product = new ProductBuilder().WithName(name).Build(); 24 | product.Info.Name.Should().Be(name); 25 | } 26 | 27 | [TestMethod] 28 | public void GivenProduct_WhenPriceLessThanZero_ThenThrow() 29 | { 30 | Action action = () => _ = new ProductBuilder().WithPrice(-10).Build(); 31 | action.Should().Throw().WithMessage("'Price' must be greater than or equal to 0."); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/Products/ValueObjects/PictureTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.ValueObjects; 2 | using DDDMart.SharedKernel.Exceptions; 3 | 4 | namespace DDDMart.Catalogue.Core.Tests.ValueObjects 5 | { 6 | [TestClass] 7 | public class PictureTests 8 | { 9 | [TestMethod] 10 | public void GivenPicture_WhenCreate_ThenCreate() 11 | { 12 | var info = Picture.Create("name", "https://test.com"); 13 | info.Name.Should().Be("name"); 14 | } 15 | 16 | [TestMethod] 17 | public void GivenPicture_WhenInvalidUrl_ThenThrow() 18 | { 19 | Action action = () => Picture.Create("name", "https:test.com"); 20 | action.Should().Throw().WithMessage("Must have a valid Uri."); 21 | } 22 | 23 | [TestMethod] 24 | public void GivenPicture_WhenCreateSameValue_ThenEquals() 25 | { 26 | var info1 = Picture.Create("name", "https://test.com"); 27 | var info2 = Picture.Create("name", "https://test.com"); 28 | info1.Should().Be(info2); 29 | info1.GetHashCode().Should().Be(info2.GetHashCode()); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/Products/ValueObjects/ProductInfoTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Products.ValueObjects; 2 | using DDDMart.SharedKernel.Exceptions; 3 | 4 | namespace DDDMart.Catalogue.Core.Tests.ValueObjects 5 | { 6 | [TestClass] 7 | public class ProductInfoTests 8 | { 9 | [TestMethod] 10 | public void GivenProductInfo_WhenCreate_ThenCreate() 11 | { 12 | var info = ProductInfo.Create("name", "description"); 13 | info.Name.Should().Be("name"); 14 | } 15 | 16 | [TestMethod] 17 | public void GivenProductInfo_WhenMissingName_ThenThrow() 18 | { 19 | Action action = () => ProductInfo.Create("", "description"); 20 | action.Should().Throw().WithMessage("Required input 'Name' is missing."); 21 | } 22 | 23 | [TestMethod] 24 | public void GivenProductInfo_WhenCreateSameValue_ThenEquals() 25 | { 26 | var info1 = ProductInfo.Create("name", "description"); 27 | var info2 = ProductInfo.Create("name", "description"); 28 | info1.Should().Be(info2); 29 | info1.GetHashCode().Should().Be(info2.GetHashCode()); 30 | } 31 | 32 | [TestMethod] 33 | public void GivenProductInfo_WhenCreateDifferentValue_ThenNotEquals() 34 | { 35 | var info1 = ProductInfo.Create("name", "description"); 36 | var info2 = ProductInfo.Create("name2", "description2"); 37 | info1.Should().NotBe(info2); 38 | info1.GetHashCode().Should().NotBe(info2.GetHashCode()); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/Catalogue/DDDMart.Catalogue.Core.Tests/Reviews/Entities/ReviewTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Catalogue.Core.Reviews.DomainEvents; 2 | using DDDMart.Catalogue.Core.Reviews.ValueObjects; 3 | using DDDMart.Catalogue.Core.Tests.Builders; 4 | using DDDMart.Core.Tests; 5 | using DDDMart.SharedKernel.Exceptions; 6 | 7 | namespace DDDMart.Catalogue.Core.Tests.Reviews.Entities 8 | { 9 | [TestClass] 10 | public class ReviewTests 11 | { 12 | [TestMethod] 13 | public void GivenReview_WhenCreateValid_ThenCreate() 14 | { 15 | var comment = Comment.Create("Test comment."); 16 | var review = new ReviewBuilder() 17 | .WithComment(comment.Value) 18 | .Build(); 19 | 20 | review.Comment.Should().Be(comment); 21 | review.DomainEvents.Where(e => e is ReviewCreatedDomainEvent).Should().HaveCount(1); 22 | } 23 | 24 | [TestMethod] 25 | public void GivenReview_WhenUpdate_ThenUpdateRatingAndComment() 26 | { 27 | var comment = Comment.Create("Test comment."); 28 | var rating = Rating.Create(5); 29 | var review = new ReviewBuilder() 30 | .Build(); 31 | review.Update(rating, comment); 32 | 33 | review.Comment.Should().Be(comment); 34 | review.Rating.Should().Be(rating); 35 | review.DomainEvents.Where(e => e is ReviewUpdatedDomainEvent).Should().HaveCount(1); 36 | } 37 | 38 | [TestMethod] 39 | public void GivenReview_WhenWhitespaceAfterComment_ThenTrimComment() 40 | { 41 | var review = new ReviewBuilder() 42 | .WithComment("Whitespace after comment ") 43 | .Build(); 44 | 45 | review.Comment.Value.Should().Be("Whitespace after comment"); 46 | } 47 | 48 | [TestMethod] 49 | public void GivenReview_WhenCommentTooLong_ThenError() 50 | { 51 | var review = new ReviewBuilder() 52 | .WithComment(StringGenerator.WithLength(201)); 53 | 54 | Action action = () => review.Build(); 55 | 56 | action.Should().Throw().WithMessage("'Comment' length must be less than or equal to 200."); 57 | } 58 | 59 | [TestMethod] 60 | public void GivenReview_WhenCommentNull_ThenError() 61 | { 62 | var review = new ReviewBuilder() 63 | .WithComment(null); 64 | 65 | Action action = () => review.Build(); 66 | 67 | action.Should().Throw().WithMessage("Required input 'Comment' is missing."); 68 | } 69 | 70 | [TestMethod] 71 | public void GivenReview_WhenRatingTooHigh_ThenError() 72 | { 73 | var review = new ReviewBuilder() 74 | .WithRating(6); 75 | 76 | Action action = () => review.Build(); 77 | 78 | action.Should().Throw().WithMessage("'Rating' must be less than or equal to 5."); 79 | } 80 | 81 | [TestMethod] 82 | public void GivenReview_WhenRatingTooLow_ThenError() 83 | { 84 | var review = new ReviewBuilder() 85 | .WithRating(0); 86 | 87 | Action action = () => review.Build(); 88 | 89 | action.Should().Throw().WithMessage("'Rating' must be greater than or equal to 1."); 90 | } 91 | 92 | [TestMethod] 93 | public void GivenReview_WhenRespond_ThenAddResponse() 94 | { 95 | var review = new ReviewBuilder() 96 | .Build(); 97 | 98 | var comment = Comment.Create("response"); 99 | review.Respond(GetResponder(), comment, DateTime.UtcNow); 100 | 101 | review.Responses.Should().HaveCount(1); 102 | review.DomainEvents.Where(e => e is ReviewResponseCreatedDomainEvent).Should().HaveCount(1); 103 | } 104 | 105 | [TestMethod] 106 | public void GivenReview_WhenDeleteResponse_ThenRemove() 107 | { 108 | var review = new ReviewBuilder() 109 | .Build(); 110 | 111 | var responder = GetResponder(); 112 | var comment = Comment.Create("response"); 113 | review.Respond(responder, comment, DateTime.UtcNow); 114 | review.DeleteResponse(review.Responses.First().Id, responder, DateTime.UtcNow); 115 | 116 | review.Responses.Should().HaveCount(0); 117 | } 118 | 119 | [TestMethod] 120 | public void GivenReview_WhenUpdateResponse_ThenUpdate() 121 | { 122 | var review = new ReviewBuilder() 123 | .Build(); 124 | 125 | var responder = GetResponder(); 126 | var comment = Comment.Create("response"); 127 | var updatedComment = Comment.Create("updated response"); 128 | review.Respond(responder, comment, DateTime.UtcNow); 129 | review.EditResponse(review.Responses.First().Id, responder, updatedComment, DateTime.UtcNow); 130 | 131 | review.Responses.Single().Comment.Should().Be(updatedComment); 132 | } 133 | 134 | [TestMethod] 135 | public void GivenReview_WhenDeleteUnknownResponse_ThenNotFound() 136 | { 137 | var review = new ReviewBuilder() 138 | .Build(); 139 | 140 | var responder = GetResponder(); 141 | Action action = () => review.DeleteResponse(Guid.NewGuid(), responder, DateTime.UtcNow); 142 | 143 | action.Should().Throw(); 144 | } 145 | 146 | [TestMethod] 147 | public void GivenReview_WhenDeleteWrongCustomerResponse_ThenUnauthorized() 148 | { 149 | var review = new ReviewBuilder() 150 | .Build(); 151 | 152 | var responder1 = GetResponder("responder 1"); 153 | var responder2 = GetResponder("responder 2"); 154 | var comment = Comment.Create("response"); 155 | review.Respond(responder1, comment, DateTime.UtcNow); 156 | Action action = () => review.DeleteResponse(review.Responses.First().Id, responder2, DateTime.UtcNow); 157 | 158 | action.Should().Throw(); 159 | } 160 | 161 | [TestMethod] 162 | public void GivenReview_WhenCreateResponseOnRatingOver6MonthsOld_ThenError() 163 | { 164 | var review = new ReviewBuilder() 165 | .Build(); 166 | 167 | var comment = Comment.Create("response"); 168 | Action action = () => review.Respond(GetResponder(), comment, DateTime.UtcNow.AddMonths(7)); 169 | 170 | action.Should().Throw(); 171 | } 172 | 173 | private static Customer GetResponder(string name = "Responder 1") 174 | { 175 | return new Customer(Guid.NewGuid(), name); 176 | } 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /tests/DDDMart.Core.Tests/DDDMart.Core.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.0 5 | 10.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /tests/DDDMart.Core.Tests/StringGenerator.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace DDDMart.Core.Tests 3 | { 4 | public static class StringGenerator 5 | { 6 | public static string WithLength(int length, char character = 'x') 7 | { 8 | return string.Join("", Enumerable.Range(0, length).Select(e => character).ToArray()); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/Baskets/Entities/BasketTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.DomainEvents; 2 | using DDDMart.Ordering.Core.Common.ValueObjects; 3 | using DDDMart.Ordering.Core.Tests.Builders; 4 | using DDDMart.SharedKernel.Exceptions; 5 | 6 | namespace DDDMart.Ordering.Core.Tests.Baskets.Entities 7 | { 8 | [TestClass] 9 | public class BasketTests 10 | { 11 | [TestMethod] 12 | public void GivenBasket_WhenCreate_ThenNotCheckedOut() 13 | { 14 | var basket = new BasketBuilder().Build(); 15 | basket.CheckedOut.Should().BeFalse(); 16 | } 17 | 18 | [TestMethod] 19 | public void GivenBasket_WhenAddSameProduct_ThenAddToBasketItem() 20 | { 21 | var basket = new BasketBuilder().Build(); 22 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 23 | basket.AddItem(sqlProduct); 24 | basket.AddItem(sqlProduct); 25 | basket.Items.Should().HaveCount(1); 26 | basket.Items.First().Quantity.Should().Be(2); 27 | } 28 | 29 | [TestMethod] 30 | public void GivenBasket_WhenRemoveSameProduct_ThenReduceQuantity() 31 | { 32 | var basket = new BasketBuilder().Build(); 33 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 34 | basket.AddItem(sqlProduct); 35 | basket.AddItem(sqlProduct); 36 | basket.RemoveItem(sqlProduct); 37 | basket.Items.First().Quantity.Should().Be(1); 38 | } 39 | 40 | [TestMethod] 41 | public void GivenBasket_WhenRemoveProductFromEmptyBasket_ThenThrow() 42 | { 43 | var basket = new BasketBuilder().Build(); 44 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 45 | Action action = () => basket.RemoveItem(sqlProduct); 46 | action.Should().Throw(); 47 | } 48 | 49 | [TestMethod] 50 | public void GivenBasket_WhenCheckout_ThenSetCheckoutOut() 51 | { 52 | var basket = new BasketBuilder().Build(); 53 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 54 | basket.AddItem(sqlProduct); 55 | basket.Checkout(); 56 | basket.CheckedOut.Should().BeTrue(); 57 | basket.DomainEvents.Where(e => e is BasketCheckedOutDomainEvent).Should().HaveCount(1); 58 | } 59 | 60 | [TestMethod] 61 | public void GivenBasket_WhenCheckoutEmptyBasket_ThenThrow() 62 | { 63 | var basket = new BasketBuilder().Build(); 64 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 65 | Action action = () => basket.Checkout(); 66 | action.Should().Throw().WithMessage("Cannot check-out as the basket is empty"); 67 | } 68 | 69 | [TestMethod] 70 | public void GivenBasket_WhenCheckoutAlreadyCheckedOut_ThenThrow() 71 | { 72 | var basket = new BasketBuilder().Build(); 73 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 74 | basket.AddItem(sqlProduct); 75 | basket.Checkout(); 76 | Action action = () => basket.Checkout(); 77 | action.Should().Throw().WithMessage("The basket is already checked-out"); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/Builders/AddressBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Orders.Factories; 2 | using DDDMart.Ordering.Core.Orders.ValueObjects; 3 | 4 | namespace DDDMart.Ordering.Core.Tests.Builders 5 | { 6 | public class AddressBuilder 7 | { 8 | private readonly AddressFactory _factory = new AddressFactory(); 9 | private string _street = "1 Feather Lane"; 10 | private string _city = "Test City"; 11 | private string _state = "New York"; 12 | private string _zipCode = "536354"; 13 | private string _country = "USA"; 14 | 15 | public ShippingAddress BuildShipping() 16 | { 17 | return _factory.CreateShipping(_street, _city, _state, _country, _zipCode); 18 | } 19 | 20 | public PaymentAddress BuildPayment() 21 | { 22 | return _factory.CreatePayment(_street, _city, _state, _country, _zipCode); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/Builders/BasketBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.Entities; 2 | 3 | namespace DDDMart.Ordering.Core.Tests.Builders 4 | { 5 | public class BasketBuilder 6 | { 7 | private Guid _customerId = Guid.NewGuid(); 8 | 9 | public Basket Build() 10 | { 11 | return Basket.Create(_customerId); 12 | } 13 | 14 | public BasketBuilder WithCustomerId(Guid id) 15 | { 16 | _customerId = id; 17 | return this; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/Builders/OrderBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Common.ValueObjects; 2 | using DDDMart.Ordering.Core.Orders.Entities; 3 | 4 | namespace DDDMart.Ordering.Core.Tests.Builders 5 | { 6 | public class OrderBuilder 7 | { 8 | private Guid _customerId = Guid.NewGuid(); 9 | 10 | public Order Build() 11 | { 12 | var basket = new BasketBuilder() 13 | .WithCustomerId(_customerId) 14 | .Build(); 15 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 16 | basket.AddItem(sqlProduct); 17 | return Order.FromBasket(basket); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/DDDMart.Ordering.Core.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | global using FluentAssertions; 3 | global using Moq; -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/Orders/DomainEventHandlers/BasketCheckedOutDomainEventHandlerTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.DomainEvents; 2 | using DDDMart.Ordering.Core.Baskets.Repositories; 3 | using DDDMart.Ordering.Core.Orders.DomainEventHandlers; 4 | using DDDMart.Ordering.Core.Orders.Entities; 5 | using DDDMart.Ordering.Core.Orders.Repositories; 6 | using DDDMart.Ordering.Core.Tests.Builders; 7 | using Microsoft.Extensions.Logging; 8 | 9 | namespace DDDMart.Ordering.Core.Tests.Orders.DomainEventHandlers 10 | { 11 | [TestClass] 12 | public class BasketCheckedOutDomainEventHandlerTests 13 | { 14 | private readonly BasketCheckedOutDomainEventHandler _handler; 15 | private readonly Mock _basketsRepository = new Mock(); 16 | private readonly Mock _ordersRepository = new Mock(); 17 | 18 | public BasketCheckedOutDomainEventHandlerTests() 19 | { 20 | _handler = new BasketCheckedOutDomainEventHandler(_basketsRepository.Object, _ordersRepository.Object, Mock.Of>()); 21 | } 22 | 23 | [TestMethod] 24 | public async Task GivenBasketCheckedOutDomainEvent_WhenHandle_ThenCreateOrder() 25 | { 26 | var basket = new BasketBuilder().Build(); 27 | _basketsRepository.Setup(e => e.GetByIdAsync(basket.Id)).ReturnsAsync(basket); 28 | 29 | await _handler.HandleAsync(new BasketCheckedOutDomainEvent(basket.Id, basket.CustomerId)); 30 | 31 | _ordersRepository.Verify(e => e.InsertAsync(It.Is(order => order.BasketId == basket.Id && order.CustomerId == basket.CustomerId)), Times.Once); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Core.Tests/Orders/Entities/OrderTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Common.ValueObjects; 2 | using DDDMart.Ordering.Core.Orders.DomainEvents; 3 | using DDDMart.Ordering.Core.Orders.Entities; 4 | using DDDMart.Ordering.Core.Orders.ValueObjects; 5 | using DDDMart.Ordering.Core.Tests.Builders; 6 | using DDDMart.SharedKernel.Exceptions; 7 | 8 | namespace DDDMart.Ordering.Core.Tests.Orders.Entities 9 | { 10 | [TestClass] 11 | public class OrderTests 12 | { 13 | [TestMethod] 14 | public void GivenOrder_WhenCreate_ThenDraftStatus() 15 | { 16 | var order = new OrderBuilder().Build(); 17 | order.Status.Should().Be(OrderStatus.Draft); 18 | order.DispatchedDate.Should().BeNull(); 19 | order.DeliveredDate.Should().BeNull(); 20 | } 21 | 22 | [TestMethod] 23 | public void GivenOrder_WhenCancel_ThenSetCancelled() 24 | { 25 | var order = new OrderBuilder().Build(); 26 | order.Cancel(); 27 | order.Status.Should().Be(OrderStatus.Cancelled); 28 | order.DomainEvents.Where(e => e is OrderCancelledDomainEvent).Should().HaveCount(1); 29 | } 30 | 31 | [TestMethod] 32 | public void GivenOrder_WhenCreateWithBasketItems_ThenAddItems() 33 | { 34 | var basket = new BasketBuilder().Build(); 35 | var sqlProduct = new OrderProduct(Guid.NewGuid(), "SQL Server", 100); 36 | basket.AddItem(sqlProduct); 37 | basket.AddItem(sqlProduct); 38 | var order = Order.FromBasket(basket); 39 | order.Items.Should().HaveCount(1); 40 | order.Items.First().Quantity.Should().Be(2); 41 | } 42 | 43 | [TestMethod] 44 | public void GivenOrder_WhenUpdateShippingAddress_ThenUpdateStatusAndAddress() 45 | { 46 | var order = new OrderBuilder().Build(); 47 | order.UpdateShippingAddress(new AddressBuilder().BuildShipping()); 48 | order.Status.Should().Be(OrderStatus.ShippingAddressConfirmed); 49 | order.ShippingAddress.Should().NotBeNull(); 50 | } 51 | 52 | [TestMethod] 53 | public void GivenOrder_WhenUpdatePaymentMethod_ThenUpdateStatusAndAddress() 54 | { 55 | var order = new OrderBuilder().Build(); 56 | order.UpdateShippingAddress(new AddressBuilder().BuildShipping()); 57 | order.UpdatePaymentMethod(Guid.NewGuid(), new AddressBuilder().BuildPayment()); 58 | order.Status.Should().Be(OrderStatus.PaymentMethodConfirmed); 59 | order.PaymentAddress.Should().NotBeNull(); 60 | } 61 | 62 | [TestMethod] 63 | public void GivenOrder_WhenUpdatePaymentMethodBeforeShippingAddress_ThenThrow() 64 | { 65 | var order = new OrderBuilder().Build(); 66 | Action action = () => order.UpdatePaymentMethod(Guid.NewGuid(), new AddressBuilder().BuildPayment()); 67 | action.Should().Throw().WithMessage("Shipping Address must be selected before Payment Method"); 68 | } 69 | 70 | [TestMethod] 71 | public void GivenOrder_WhenSubmit_ThenUpdateStatus() 72 | { 73 | var order = new OrderBuilder().Build(); 74 | order.UpdateShippingAddress(new AddressBuilder().BuildShipping()); 75 | order.UpdatePaymentMethod(Guid.NewGuid(), new AddressBuilder().BuildPayment()); 76 | order.Submit(); 77 | order.Status.Should().Be(OrderStatus.Submitted); 78 | order.DomainEvents.Where(e => e is OrderSubmittedDomainEvent).Should().HaveCount(1); 79 | } 80 | 81 | [TestMethod] 82 | public void GivenOrder_WhenSubmitCancelled_ThenThrow() 83 | { 84 | var order = new OrderBuilder().Build(); 85 | order.UpdateShippingAddress(new AddressBuilder().BuildShipping()); 86 | order.UpdatePaymentMethod(Guid.NewGuid(), new AddressBuilder().BuildPayment()); 87 | order.Cancel(); 88 | Action action = () => order.Submit(); 89 | action.Should().Throw().WithMessage("Order has been cancelled."); 90 | } 91 | 92 | [TestMethod] 93 | public void GivenOrder_WhenSubmitBeforeComplete_ThenThrow() 94 | { 95 | var order = new OrderBuilder().Build(); 96 | Action action = () => order.Submit(); 97 | action.Should().Throw(); 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Infrastructure.Tests/DDDMart.Ordering.Infrastructure.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Infrastructure.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | global using FluentAssertions; 3 | global using Moq; -------------------------------------------------------------------------------- /tests/Ordering/DDDMart.Ordering.Infrastructure.Tests/Repositories/OrdersRepositoryTests.cs: -------------------------------------------------------------------------------- 1 | using Autofac; 2 | using DDDMart.Ordering.Application.Services; 3 | using DDDMart.Ordering.Core.Orders.Entities; 4 | using DDDMart.Ordering.Core.Orders.Repositories; 5 | using DDDMart.Ordering.Core.Tests.Builders; 6 | using DDDMart.Ordering.Infrastructure.AutofacModules; 7 | using DDDMart.SharedKernel; 8 | using MediatR; 9 | using Microsoft.EntityFrameworkCore; 10 | 11 | namespace DDDMart.Ordering.Infrastructure.Tests.Repositories 12 | { 13 | [TestClass] 14 | public class OrdersRepositoryTests 15 | { 16 | private readonly IOrdersRepository _ordersRepository; 17 | private readonly Mock _mediator = new Mock(); 18 | private readonly IContainer _container; 19 | 20 | public OrdersRepositoryTests() 21 | { 22 | var builder = new ContainerBuilder(); 23 | builder.RegisterModule(new OrderingInfrastructureModule()); 24 | builder.RegisterInstance(new OrderingIntegrationEventMapper()).AsImplementedInterfaces(); 25 | builder.RegisterInstance(_mediator.Object); 26 | _container = builder.Build(); 27 | _ordersRepository = _container.Resolve(); 28 | } 29 | 30 | [TestMethod] 31 | public async Task GivenOrdersRepository_WhenInsert_ThenCanGetById() 32 | { 33 | var order = await GenerateAsync(); 34 | var inserted = await _ordersRepository.GetByIdAsync(order.Id); 35 | inserted.Should().NotBeNull(); 36 | } 37 | 38 | [TestMethod] 39 | public async Task GivenOrdersRepository_WhenHasEvent_ThenAddToOutbox() 40 | { 41 | var order = await GenerateAsync(); 42 | order.Cancel(); 43 | await _ordersRepository.UnitOfWork.CommitAsync(); 44 | _mediator.Verify(e => e.Publish(It.IsAny(), It.IsAny()), Times.Once); 45 | 46 | var context = _container.Resolve(); 47 | context.OutboxIntegrationEvents.Count().Should().Be(1); 48 | } 49 | 50 | [TestMethod] 51 | public async Task GivenOrdersRepository_WhenInsert_ThenCanGet() 52 | { 53 | var order = await GenerateAsync(); 54 | var inserted = await _ordersRepository.GetAll().FirstOrDefaultAsync(e => e.Id == order.Id); 55 | inserted.Should().NotBeNull(); 56 | } 57 | 58 | [TestMethod] 59 | public async Task GivenOrdersRepository_WhenInsert_ThenCanGetWithTracking() 60 | { 61 | var order = await GenerateAsync(); 62 | var inserted = await _ordersRepository.GetAll(false).FirstOrDefaultAsync(e => e.Id == order.Id); 63 | inserted.Should().NotBeNull(); 64 | } 65 | 66 | [TestMethod] 67 | public async Task GivenOrdersRepository_WhenDelete_ThenCantGet() 68 | { 69 | var order = await GenerateAsync(); 70 | _ordersRepository.Delete(order); 71 | await _ordersRepository.UnitOfWork.CommitAsync(); 72 | await AssertDoesNotExist(order.Id); 73 | } 74 | 75 | [TestMethod] 76 | public async Task GivenOrdersRepository_WhenRemove_ThenCantGet() 77 | { 78 | var order = await GenerateAsync(); 79 | _ordersRepository.Remove(new List() { order }); 80 | await _ordersRepository.UnitOfWork.CommitAsync(); 81 | await AssertDoesNotExist(order.Id); 82 | } 83 | 84 | private async Task GenerateAsync() 85 | { 86 | var order = new OrderBuilder().Build(); 87 | await _ordersRepository.InsertAsync(order); 88 | await _ordersRepository.UnitOfWork.CommitAsync(); 89 | return order; 90 | } 91 | 92 | private async Task AssertDoesNotExist(Guid id) 93 | { 94 | var order = await _ordersRepository.GetByIdAsync(id); 95 | order.Should().BeNull(); 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Application.Tests/DDDMart.Payments.Application.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Application.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | global using FluentAssertions; 3 | global using Moq; -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Application.Tests/IntegrationEventHandlers/OrderSubmittedIntegrationEventHandlerTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Application.IntegrationEvents; 2 | using DDDMart.Payments.Application.IntegrationEvents.Handlers; 3 | using DDDMart.Payments.Core.Invoices.Entities; 4 | using DDDMart.Payments.Core.Invoices.Repositories; 5 | using DDDMart.SharedKernel; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace DDDMart.Payments.Application.Tests.IntegrationEventHandlers 9 | { 10 | [TestClass] 11 | public class OrderSubmittedIntegrationEventHandlerTests 12 | { 13 | private readonly OrderSubmittedIntegrationEventHandler _handler; 14 | private readonly Mock _invoicesRepository = new Mock(); 15 | 16 | public OrderSubmittedIntegrationEventHandlerTests() 17 | { 18 | _invoicesRepository.Setup(e => e.UnitOfWork).Returns(Mock.Of()); 19 | _handler = new OrderSubmittedIntegrationEventHandler(Mock.Of>(), _invoicesRepository.Object); 20 | } 21 | 22 | [TestMethod] 23 | public async Task GivenOrderSubmittedIntegrationEventHandler_WhenHandler_ThenGenerateInvoice() 24 | { 25 | var @event = new OrderSubmittedIntegrationEvent(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), "Street", "City", "State", "Country", "4324324", 100); 26 | 27 | await _handler.HandleAsync(@event); 28 | 29 | _invoicesRepository.Verify(e => e.InsertAsync(It.Is(invoice => invoice.OrderId == @event.Id)), Times.Once); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Application.Tests/Services/PaymentsIntegrationEventMapperTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Ordering.Core.Baskets.DomainEvents; 2 | using DDDMart.Payments.Application.IntegrationEvents; 3 | using DDDMart.Payments.Application.Services; 4 | using DDDMart.Payments.Core; 5 | using DDDMart.Payments.Core.Invoices.DomainEvents; 6 | using DDDMart.SharedKernel; 7 | 8 | namespace DDDMart.Payments.Application.Tests.Services 9 | { 10 | [TestClass] 11 | public class PaymentsIntegrationEventMapperTests 12 | { 13 | private readonly IPaymentsIntegrationEventMapper _eventMapper = new PaymentsIntegrationEventMapper(); 14 | 15 | [TestMethod] 16 | public void GivenPaymentsIntegrationEventMapper_WhenMapMappedDomainEvent_ThenCreateIntegrationEvent() 17 | { 18 | var integrationEvents = _eventMapper.Map(new List() { new InvoicePaidDomainEvent(Guid.NewGuid(), DateTime.UtcNow, Guid.NewGuid(), Guid.NewGuid()) }); 19 | integrationEvents.Should().HaveCount(1); 20 | integrationEvents.First().EventName.Should().Be(nameof(InvoicePaidIntegrationEvent)); 21 | } 22 | 23 | [TestMethod] 24 | public void GivenPaymentsIntegrationEventMapper_WhenMapNonMappedDomainEvent_ThenMapEmpty() 25 | { 26 | var integrationEvents = _eventMapper.Map(new List() { new BasketCheckedOutDomainEvent(Guid.NewGuid(), Guid.NewGuid()) }); 27 | integrationEvents.Should().HaveCount(0); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Core.Tests/Builders/InvoiceBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.Invoices.Entities; 2 | using DDDMart.Payments.Core.Invoices.ValueObjects; 3 | 4 | namespace DDDMart.Payments.Core.Tests.Builders 5 | { 6 | public class InvoiceBuilder 7 | { 8 | private Guid _customerId = Guid.NewGuid(); 9 | private Guid _paymentMethodId = Guid.NewGuid(); 10 | private Guid _orderId = Guid.NewGuid(); 11 | private string _street = "1 Feather Lane"; 12 | private string _city = "Test City"; 13 | private string _state = "New York"; 14 | private string _zipCode = "536354"; 15 | private string _country = "USA"; 16 | private decimal _amount = 100; 17 | 18 | public Invoice Build() 19 | { 20 | return Invoice.Generate(_customerId, _orderId, _paymentMethodId, InvoiceAddress.Create(_street, _city, _state, _country, _zipCode), _amount); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Core.Tests/Builders/PaymentMethodBuilder.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.PaymentMethods.Entities; 2 | using DDDMart.Payments.Core.PaymentMethods.ValueObjects; 3 | 4 | namespace DDDMart.Payments.Core.Tests.Builders 5 | { 6 | public class PaymentMethodBuilder 7 | { 8 | private string _name = "Credit Card"; 9 | private Guid _customerId = Guid.NewGuid(); 10 | private PaymentType _type = PaymentType.CreditCard; 11 | 12 | public PaymentMethod Build() 13 | { 14 | return PaymentMethod.Create(_name, _customerId, _type); 15 | } 16 | 17 | public PaymentMethodBuilder WithName(string name) 18 | { 19 | _name = name; 20 | return this; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Core.Tests/DDDMart.Payments.Core.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | false 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | all 16 | runtime; build; native; contentfiles; analyzers; buildtransitive 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Core.Tests/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | global using FluentAssertions; 3 | global using Moq; -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Core.Tests/Invoices/Entities/InvoiceTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.Invoices.DomainEvents; 2 | using DDDMart.Payments.Core.Invoices.ValueObjects; 3 | using DDDMart.Payments.Core.Tests.Builders; 4 | 5 | namespace DDDMart.Payments.Core.Tests.Invoices.Entities 6 | { 7 | [TestClass] 8 | public class InvoiceTests 9 | { 10 | [TestMethod] 11 | public void GivenInvoice_WhenCreate_ThenCreateNotPaid() 12 | { 13 | var invoice = new InvoiceBuilder().Build(); 14 | invoice.Should().NotBeNull(); 15 | invoice.Status.Should().Be(InvoiceStatus.NotPaid); 16 | invoice.Paid.Should().BeFalse(); 17 | invoice.PaidDate.Should().BeNull(); 18 | } 19 | 20 | [TestMethod] 21 | public void GivenInvoice_WhenPay_ThenPay() 22 | { 23 | var invoice = new InvoiceBuilder().Build(); 24 | invoice.Pay(); 25 | invoice.Status.Should().Be(InvoiceStatus.Paid); 26 | invoice.Paid.Should().BeTrue(); 27 | invoice.PaidDate.Should().NotBeNull(); 28 | invoice.DomainEvents.Where(e => e is InvoicePaidDomainEvent).Should().HaveCount(1); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /tests/Payments/DDDMart.Payments.Core.Tests/PaymentMethods/Entities/PaymentMethodTests.cs: -------------------------------------------------------------------------------- 1 | using DDDMart.Payments.Core.Tests.Builders; 2 | 3 | namespace DDDMart.Payments.Core.Tests.PaymentMethods.Entities 4 | { 5 | [TestClass] 6 | public class PaymentMethodTests 7 | { 8 | [TestMethod] 9 | public void GivenPaymentMethod_WhenCreate_ThenCreate() 10 | { 11 | var name = "Personal"; 12 | var paymentMethod = new PaymentMethodBuilder().WithName(name).Build(); 13 | paymentMethod.Name.Should().Be(name); 14 | } 15 | } 16 | } 17 | --------------------------------------------------------------------------------