├── .gitignore
├── CREATE DATABASE.sql
├── README.md
├── docker-compose.yaml
└── src
├── SampleOutboxPattern.API
├── Program.cs
├── Properties
│ └── launchSettings.json
├── SampleOutboxPattern.API.csproj
├── appsettings.Development.json
└── appsettings.json
├── SampleOutboxPattern.Infrastructure.Domain
├── AggregateRoot.cs
├── IEvent.cs
└── SampleOutboxPattern.Infrastructure.Domain.csproj
├── SampleOutboxPattern.Infrastructure.Messaging
├── JsonSerializerUTF8.cs
├── KafkaProducer.cs
└── SampleOutboxPattern.Infrastructure.Messaging.csproj
├── SampleOutboxPattern.Orders.Application
├── Events
│ ├── CustomerOrderPlacedV1.cs
│ └── EventBase.cs
├── Models
│ ├── Order.cs
│ └── OrderItem.cs
├── OrderService.cs
├── Repository
│ └── OrderRepository.cs
├── RequestModels
│ ├── CustomerOrderRequest.cs
│ └── ProductDto.cs
└── SampleOutboxPattern.Orders.Application.csproj
└── SampleOutboxPattern.sln
/.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 | /videos
352 |
--------------------------------------------------------------------------------
/CREATE DATABASE.sql:
--------------------------------------------------------------------------------
1 | CREATE DATABASE OrderManagement;
2 |
3 | GO
4 |
5 | USE OrderManagement;
6 |
7 | GO
8 |
9 | CREATE TABLE Orders
10 | (
11 | Id INT IDENTITY(1,1) PRIMARY KEY,
12 | CustomerId VARCHAR(200) NOT NULL,
13 | TotalItems DECIMAL(18,2) NOT NULL,
14 | Total DECIMAL(18,2) NOT NULL,
15 | CreatedAt DATE NOT NULL
16 | )
17 |
18 | CREATE TABLE OrderDetails
19 | (
20 | OrderId INT NOT NULL,
21 | Sku VARCHAR(10) NOT NULL,
22 | Name VARCHAR(200) NOT NULL,
23 | UnitPrice DECIMAL(18,2) NOT NULL,
24 | Quantity INT NOT NULL,
25 | LineNumber INT NOT NULL,
26 | CONSTRAINT OrderDetails_Pk PRIMARY KEY (OrderId, Sku)
27 | )
28 |
29 | ALTER TABLE OrderDetails ADD CONSTRAINT OrderDetails_Order
30 | FOREIGN KEY (OrderId)
31 | REFERENCES Orders (Id);
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Event-Driven: Outbox Pattern
2 | Trabalhar em sistemas distribuídos é um grande desafio, dado a grande quantidade de conceitos e padrões computacionais que um engenheiro de sistemas precisa conhecer e saber aplicar.
3 |
4 | Nesse tipo de sistemas, fica evidente que o estilo arquitetural Event-Driven começa a ser um padrão adotado para resolver problemas na comunicação entre os serviços, trazendo uma maior responsividade - _Neste caso, otimizar o tempo de resposta das aplicações_, às aplicações.
5 |
6 | Implementar uma arquitetura distribída com base em Event-Driven traz alguns desafios, e um deles é a Garantia da Entrega de mensagens ou [Guaranteed Delivery](https://www.enterpriseintegrationpatterns.com/patterns/messaging/GuaranteedMessaging.html), que é um padrão de design com o qual, uma arquitetura passa a dar a capacidade de resposta de que, mesmo usando Microsserviços, a plataforma como um todo, passe a dar garantias de que as mensagens transitarão de um serviço para o outro, através de mensageria e processamentos em background.
7 |
8 | Esse repositório traz a implementação do padrão arquitetural Outbox Pattern em um projeto usando as seguintes tecnologias:
9 |
10 | - [.NET 6](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) (como Minimal API)
11 | - [SQL Server](https://www.microsoft.com/en-us/sql-server/sql-server-downloads)
12 | - [Apache Kafka](https://kafka.apache.org/)
13 | - [Docker](https://www.docker.com/)
14 |
15 | Para rodar o projeto, faça o clone do projeto e rode a linha de comando abaixo para subir os containers:
16 |
17 | ```shell
18 | > docker-compose -f docker-compose.yaml up -d
19 | ```
20 |
21 | ⚠️ PS.1: O conteúdo do docker-compose contempla APENAS o **SQL** e o **Apache Kafka**.
--------------------------------------------------------------------------------
/docker-compose.yaml:
--------------------------------------------------------------------------------
1 | version: '3.4'
2 |
3 | services:
4 | sqlserver:
5 | image: mcr.microsoft.com/mssql/server
6 | container_name: sample-outbox-mssql
7 | hostname: mssqls-server
8 | ports:
9 | - 1433:1433
10 | environment:
11 | ACCEPT_EULA: 'Y'
12 | SA_PASSWORD: ec_om@2022
13 | DATABASE_NAME: OrderManagement
14 |
15 | zoo1:
16 | image: zookeeper:3.4.9
17 | container_name: sample-outbox-zookeeper
18 | hostname: zoo1
19 | ports:
20 | - '2181:2181'
21 | environment:
22 | ZOO_MY_ID: 1
23 | ZOO_PORT: 2181
24 |
25 | kafka:
26 | image: confluentinc/cp-kafka:5.5.1
27 | container_name: sample-outbox-kafkabroker
28 | hostname: kafka
29 | ports:
30 | - '9092:9092'
31 | - '9999:9999'
32 | environment:
33 | KAFKA_BROKER_ID: 1
34 | KAFKA_ZOOKEEPER_CONNECT: 'zoo1:2181'
35 | KAFKA_ADVERTISED_LISTENERS: LISTENER_DOCKER_INTERNAL://kafka:19092,LISTENER_DOCKER_EXTERNAL://${DOCKER_HOST_IP:-127.0.0.1}:9092
36 | KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: LISTENER_DOCKER_INTERNAL:PLAINTEXT,LISTENER_DOCKER_EXTERNAL:PLAINTEXT
37 | KAFKA_INTER_BROKER_LISTENER_NAME: LISTENER_DOCKER_INTERNAL
38 | KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
39 | depends_on:
40 | - zoo1
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.API/Program.cs:
--------------------------------------------------------------------------------
1 | using SampleOutboxPattern.Orders.Application;
2 | using SampleOutboxPattern.Orders.Application.RequestModels;
3 |
4 | var builder = WebApplication.CreateBuilder(args);
5 |
6 | builder.Services.AddEndpointsApiExplorer();
7 | builder.Services.AddSwaggerGen();
8 |
9 | var app = builder.Build();
10 |
11 | // Configure the HTTP request pipeline.
12 | if (app.Environment.IsDevelopment())
13 | {
14 | app.UseSwagger();
15 | app.UseSwaggerUI();
16 | }
17 |
18 | app.MapPost("/order", async (CustomerOrderRequest customerOrderRequest) =>
19 | {
20 | OrderService orderService = new();
21 |
22 | await orderService.PlaceCustomerOrder(customerOrderRequest);
23 | });
24 |
25 | app.Run();
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.API/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:53528",
8 | "sslPort": 0
9 | }
10 | },
11 | "profiles": {
12 | "SampleOutboxPattern.API": {
13 | "commandName": "Project",
14 | "dotnetRunMessages": true,
15 | "launchBrowser": true,
16 | "launchUrl": "swagger",
17 | "applicationUrl": "http://localhost:5244",
18 | "environmentVariables": {
19 | "ASPNETCORE_ENVIRONMENT": "Development"
20 | }
21 | },
22 | "IIS Express": {
23 | "commandName": "IISExpress",
24 | "launchBrowser": true,
25 | "launchUrl": "swagger",
26 | "environmentVariables": {
27 | "ASPNETCORE_ENVIRONMENT": "Development"
28 | }
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.API/SampleOutboxPattern.API.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.API/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.API/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "LogLevel": {
4 | "Default": "Information",
5 | "Microsoft.AspNetCore": "Warning"
6 | }
7 | },
8 | "AllowedHosts": "*"
9 | }
10 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Infrastructure.Domain/AggregateRoot.cs:
--------------------------------------------------------------------------------
1 | namespace SampleOutboxPattern.Infrastructure.Domain
2 | {
3 | public class AggregateRoot
4 | {
5 | private readonly List _events = new List();
6 |
7 | public IReadOnlyList Events => _events;
8 |
9 | protected void AddEvent(IEvent @event)
10 | {
11 | _events.Add(@event);
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Infrastructure.Domain/IEvent.cs:
--------------------------------------------------------------------------------
1 | namespace SampleOutboxPattern.Infrastructure.Domain
2 | {
3 | public interface IEvent
4 | {
5 | string PartitionKey();
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Infrastructure.Domain/SampleOutboxPattern.Infrastructure.Domain.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Infrastructure.Messaging/JsonSerializerUTF8.cs:
--------------------------------------------------------------------------------
1 | using Confluent.Kafka;
2 |
3 | using Newtonsoft.Json;
4 |
5 | using System.Text;
6 |
7 | namespace SampleOutboxPattern.Infrastructure.Messaging
8 | {
9 | public class JsonSerializerUTF8 : ISerializer
10 | {
11 | private readonly JsonSerializerSettings jsonSettings;
12 | private readonly Encoding encoder;
13 |
14 | public JsonSerializerUTF8()
15 | {
16 | jsonSettings = new JsonSerializerSettings
17 | {
18 | TypeNameHandling = TypeNameHandling.All,
19 | ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
20 | NullValueHandling = NullValueHandling.Ignore
21 | };
22 |
23 | encoder = Encoding.UTF8;
24 | }
25 |
26 | public byte[] Serialize(T data, SerializationContext context)
27 | {
28 | return encoder.GetBytes(JsonConvert.SerializeObject(data, jsonSettings));
29 | }
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Infrastructure.Messaging/KafkaProducer.cs:
--------------------------------------------------------------------------------
1 | using Confluent.Kafka;
2 |
3 | namespace SampleOutboxPattern.Infrastructure.Messaging
4 | {
5 | public class KafkaProducer : IDisposable
6 | where TEntity : class
7 | {
8 | private readonly string _topicName;
9 |
10 | private readonly ProducerConfig _producerConfig;
11 |
12 | public KafkaProducer(string topicName, string server)
13 | {
14 | _topicName = topicName;
15 |
16 | _producerConfig = new ProducerConfig
17 | {
18 | BootstrapServers = server
19 | };
20 | }
21 |
22 | public async Task ProduceMessageAsync(TEntity entity, TKeyType partitionKey)
23 | {
24 | // If serializers are not specified, default serializers from
25 | // `Confluent.Kafka.Serializers` will be automatically used where
26 | // available. Note: by default strings are encoded as UTF8.
27 | using (var p = new ProducerBuilder(_producerConfig)
28 | .SetKeySerializer(new JsonSerializerUTF8())
29 | .SetValueSerializer(new JsonSerializerUTF8())
30 | .Build())
31 | {
32 | var message = new Message
33 | {
34 | Key = partitionKey,
35 | Value = entity
36 | };
37 |
38 | await p.ProduceAsync(_topicName, message);
39 | }
40 | }
41 |
42 | public void Dispose()
43 | {
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Infrastructure.Messaging/SampleOutboxPattern.Infrastructure.Messaging.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/Events/CustomerOrderPlacedV1.cs:
--------------------------------------------------------------------------------
1 | using SampleOutboxPattern.Orders.Application.Models;
2 |
3 | namespace SampleOutboxPattern.Orders.Application.Events
4 | {
5 | internal class CustomerOrderPlacedV1 : EventBase
6 | {
7 | public CustomerOrderPlacedV1(int customerId, IEnumerable products)
8 | : base("1.0")
9 | {
10 | CustomerId = customerId;
11 | Products = products;
12 | }
13 |
14 | public int CustomerId { get; }
15 | public IEnumerable Products { get; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/Events/EventBase.cs:
--------------------------------------------------------------------------------
1 | using SampleOutboxPattern.Infrastructure.Domain;
2 |
3 | namespace SampleOutboxPattern.Orders.Application.Events
4 | {
5 | public class EventBase: IEvent
6 | {
7 | private readonly Guid _eventId;
8 |
9 | public EventBase(string version)
10 | {
11 | Version = version;
12 | OccuredAt = DateTime.UtcNow;
13 | _eventId = Guid.NewGuid();
14 | }
15 |
16 | public string EventName => this.GetType().Name;
17 |
18 | public Guid EventId => _eventId;
19 |
20 | public string Version { get; }
21 |
22 | public DateTime OccuredAt { get; }
23 |
24 | public string PartitionKey() => $"{EventName}-{this.EventId}";
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/Models/Order.cs:
--------------------------------------------------------------------------------
1 | using Dapper;
2 |
3 | using SampleOutboxPattern.Infrastructure.Domain;
4 | using SampleOutboxPattern.Orders.Application.RequestModels;
5 | using SampleOutboxPattern.Orders.Application.Events;
6 |
7 | namespace SampleOutboxPattern.Orders.Application.Models
8 | {
9 | [Table("Orders")]
10 | internal class Order : AggregateRoot
11 | {
12 | private IList _orderItems;
13 |
14 | public int Id { get; }
15 | public int CustomerId { get; }
16 | public int TotalItems => Products.Count();
17 | public decimal Total => Products.Sum(p => p.Quantity * p.Value);
18 | public DateTime CreatedAt { get; }
19 | public IEnumerable Products
20 | {
21 | get => _orderItems.ToList();
22 | set => _orderItems = value.ToList();
23 | }
24 |
25 | public Order(int customerId, IList productsDto)
26 | {
27 | Id = default;
28 | CustomerId = customerId;
29 | _orderItems = productsDto
30 | .Select(p => new OrderItem
31 | {
32 | Sku = p.Sku,
33 | Name = p.Name,
34 | Quantity = p.Quantity,
35 | Value = p.UnitPrice,
36 | })
37 | .ToList();
38 |
39 | CreatedAt = DateTime.UtcNow;
40 |
41 | AddEvent(new CustomerOrderPlacedV1(CustomerId, Products));
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/Models/OrderItem.cs:
--------------------------------------------------------------------------------
1 | using Dapper;
2 |
3 | namespace SampleOutboxPattern.Orders.Application.Models
4 | {
5 | [Table("OrderItems")]
6 | internal class OrderItem
7 | {
8 | public string? Sku { get; set; }
9 |
10 | public string? Name { get; set; }
11 |
12 | public int Quantity { get; set; }
13 |
14 | public decimal Value { get; set; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/OrderService.cs:
--------------------------------------------------------------------------------
1 | using SampleOutboxPattern.Infrastructure.Messaging;
2 | using SampleOutboxPattern.Orders.Application.Events;
3 | using SampleOutboxPattern.Orders.Application.Models;
4 | using SampleOutboxPattern.Orders.Application.Repository;
5 | using SampleOutboxPattern.Orders.Application.RequestModels;
6 |
7 | namespace SampleOutboxPattern.Orders.Application
8 | {
9 | public class OrderService
10 | {
11 | private readonly OrderRepository _orderRepository;
12 |
13 | public OrderService()
14 | {
15 | _orderRepository = new OrderRepository();
16 | }
17 |
18 | public async Task PlaceCustomerOrder(CustomerOrderRequest customerOrderRequest)
19 | {
20 | Order customerOrder = new(customerOrderRequest.CustomerId, customerOrderRequest.Products);
21 |
22 | await _orderRepository.PlaceOrder(customerOrder);
23 |
24 | foreach (var customerOrderEvent in customerOrder.Events)
25 | {
26 | try
27 | {
28 | using (var producer =
29 | new KafkaProducer(
30 | "order-events-v1",
31 | "localhost:9092"))
32 | {
33 | await producer.ProduceMessageAsync(/*(dynamic)*/(CustomerOrderPlacedV1)customerOrderEvent, customerOrderEvent.PartitionKey());
34 | }
35 | }
36 | catch
37 | {
38 | throw;
39 | }
40 | }
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/Repository/OrderRepository.cs:
--------------------------------------------------------------------------------
1 | using Dapper;
2 |
3 | using SampleOutboxPattern.Orders.Application.Models;
4 |
5 | using System.Data.SqlClient;
6 |
7 | namespace SampleOutboxPattern.Orders.Application.Repository
8 | {
9 | internal class OrderRepository
10 | {
11 | public async Task PlaceOrder(Order customerOrder)
12 | {
13 | string productsSqlStmt = "INSERT INTO ORDERDETAILS(ORDERID, SKU, NAME, UNITPRICE, QUANTITY, LINENUMBER) VALUES(@ORDERID, @SKU, @NAME, @UNITPRICE, @QUANTITY, @LINENUMBER)";
14 |
15 | try
16 | {
17 | using SqlConnection connection = new SqlConnection("Server=localhost,1433;Database=OrderManagement;User Id=sa;Password=ec_om@2022;");
18 |
19 | connection.Open();
20 |
21 | var customerOrderId = await connection.InsertAsync(customerOrder);
22 | int lineNumber = 1;
23 | foreach (var orderProduct in customerOrder.Products)
24 | {
25 | await connection.ExecuteAsync(productsSqlStmt, new
26 | {
27 | OrderId = customerOrderId,
28 | Sku = orderProduct.Sku,
29 | Name = orderProduct.Name,
30 | UnitPrice = orderProduct.Value,
31 | Quantity = orderProduct.Quantity,
32 | LineNumber = lineNumber++
33 | });
34 |
35 | // INSERT ORDER PRODUCTS
36 | }
37 |
38 | connection.Close();
39 | }
40 | catch (Exception)
41 | {
42 |
43 | throw;
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/RequestModels/CustomerOrderRequest.cs:
--------------------------------------------------------------------------------
1 | namespace SampleOutboxPattern.Orders.Application.RequestModels
2 | {
3 | public class CustomerOrderRequest
4 | {
5 | public int CustomerId { get; set; }
6 | public List Products { get; set; } = new List();
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/RequestModels/ProductDto.cs:
--------------------------------------------------------------------------------
1 | namespace SampleOutboxPattern.Orders.Application.RequestModels
2 | {
3 | public class ProductDto
4 | {
5 | public string? Sku { get; set; }
6 | public decimal UnitPrice { get; set; }
7 | public int Quantity { get; set; }
8 | public string? Name { get; set; }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.Orders.Application/SampleOutboxPattern.Orders.Application.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net6.0
5 | enable
6 | enable
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/SampleOutboxPattern.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.0.32014.148
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleOutboxPattern.API", "SampleOutboxPattern.API\SampleOutboxPattern.API.csproj", "{C4914D18-BBC5-4EC6-B999-DA235D1291B6}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleOutboxPattern.Orders.Application", "SampleOutboxPattern.Orders.Application\SampleOutboxPattern.Orders.Application.csproj", "{255D94BF-5185-46AD-B779-10B8AE6A95DB}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleOutboxPattern.Infrastructure.Messaging", "SampleOutboxPattern.Infrastructure.Messaging\SampleOutboxPattern.Infrastructure.Messaging.csproj", "{71DD8789-548F-4FC3-8E63-74C98E5CAC8D}"
11 | EndProject
12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleOutboxPattern.Infrastructure.Domain", "SampleOutboxPattern.Infrastructure.Domain\SampleOutboxPattern.Infrastructure.Domain.csproj", "{136366FA-04CD-4112-927B-B8549AB7D0CE}"
13 | EndProject
14 | Global
15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
16 | Debug|Any CPU = Debug|Any CPU
17 | Release|Any CPU = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
20 | {C4914D18-BBC5-4EC6-B999-DA235D1291B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {C4914D18-BBC5-4EC6-B999-DA235D1291B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {C4914D18-BBC5-4EC6-B999-DA235D1291B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {C4914D18-BBC5-4EC6-B999-DA235D1291B6}.Release|Any CPU.Build.0 = Release|Any CPU
24 | {255D94BF-5185-46AD-B779-10B8AE6A95DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
25 | {255D94BF-5185-46AD-B779-10B8AE6A95DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
26 | {255D94BF-5185-46AD-B779-10B8AE6A95DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
27 | {255D94BF-5185-46AD-B779-10B8AE6A95DB}.Release|Any CPU.Build.0 = Release|Any CPU
28 | {71DD8789-548F-4FC3-8E63-74C98E5CAC8D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29 | {71DD8789-548F-4FC3-8E63-74C98E5CAC8D}.Debug|Any CPU.Build.0 = Debug|Any CPU
30 | {71DD8789-548F-4FC3-8E63-74C98E5CAC8D}.Release|Any CPU.ActiveCfg = Release|Any CPU
31 | {71DD8789-548F-4FC3-8E63-74C98E5CAC8D}.Release|Any CPU.Build.0 = Release|Any CPU
32 | {136366FA-04CD-4112-927B-B8549AB7D0CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
33 | {136366FA-04CD-4112-927B-B8549AB7D0CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
34 | {136366FA-04CD-4112-927B-B8549AB7D0CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
35 | {136366FA-04CD-4112-927B-B8549AB7D0CE}.Release|Any CPU.Build.0 = Release|Any CPU
36 | EndGlobalSection
37 | GlobalSection(SolutionProperties) = preSolution
38 | HideSolutionNode = FALSE
39 | EndGlobalSection
40 | GlobalSection(ExtensibilityGlobals) = postSolution
41 | SolutionGuid = {0C16E2CE-CE70-4B45-B798-BC95D216B4B3}
42 | EndGlobalSection
43 | EndGlobal
44 |
--------------------------------------------------------------------------------