-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.html
More file actions
810 lines (715 loc) · 39.3 KB
/
index.html
File metadata and controls
810 lines (715 loc) · 39.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Concordia: A Lightweight .NET Mediator</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Highlight.js CSS for syntax highlighting -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #f8fafc; /* Tailwind: bg-slate-50 */
color: #1e293b; /* Tailwind: text-slate-800 */
}
.code-block {
background-color: #1e293b; /* Tailwind: bg-slate-800 */
color: #e2e8f0; /* Tailwind: text-slate-200 */
padding: 1rem;
border-radius: 0.5rem; /* Tailwind: rounded-lg */
overflow-x: auto;
font-family: 'Menlo', 'Monaco', 'Consolas', 'Liberation Mono', 'Courier New', monospace;
font-size: 0.875rem; /* Tailwind: text-sm */
}
.code-block pre {
margin: 0;
}
.section-title {
border-bottom: 2px solid #cbd5e1; /* Tailwind: border-slate-300 */
padding-bottom: 0.5rem;
margin-bottom: 1.5rem;
}
.nav-link {
transition: color 0.2s ease-in-out;
}
.nav-link:hover {
color: #6366f1; /* Tailwind: text-indigo-500 */
}
/* Style for the fixed left sidebar and main content area */
.page-wrapper {
display: flex;
min-height: 100vh;
}
.sidebar {
width: 250px;
flex-shrink: 0;
background-color: #f1f5f9; /* Tailwind: bg-slate-100 */
border-right: 1px solid #e2e8f0; /* Tailwind: border-slate-200 */
padding: 1.5rem;
position: fixed;
top: 0;
bottom: 0;
overflow-y: auto;
}
.main-content {
/* Offset the main content to the right of the sidebar */
margin-left: 250px;
flex-grow: 1;
padding: 2rem;
}
/* Ensure the footer also has the correct offset */
.page-footer {
margin-left: 250px;
}
/* Mobile-first approach: hide sidebar and remove offset on small screens */
@media (max-width: 768px) {
.sidebar {
display: none;
}
.main-content, .page-footer {
margin-left: 0;
}
}
</style>
</head>
<body class="antialiased">
<div class="page-wrapper">
<!-- Sidebar Navigation -->
<aside class="sidebar">
<div class="flex items-center mb-6">
<a href="#top" class="text-2xl font-bold text-indigo-600 rounded-md p-2">Concordia</a>
</div>
<nav class="flex flex-col space-y-2">
<a href="#introduction" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Introduction</a>
<a href="#getting-started" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Getting Started</a>
<a href="#installation" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Installation</a>
<a href="#usage" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Usage</a>
<a href="#migration-guide" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Migration Guide</a>
<a href="#source-code" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Source Code</a>
<a href="#contributing" class="nav-link text-slate-700 hover:text-indigo-600 font-medium rounded-md p-2 transition-colors duration-200">Contributing</a>
</nav>
</aside>
<!-- Main Content -->
<main class="main-content">
<!-- Introduction Section -->
<section id="introduction" class="mb-12">
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Introduction</h2>
<p class="text-lg leading-relaxed mb-4">
<strong>Concordia</strong> is a .NET library implementing the <strong>Mediator pattern</strong>, designed to be lightweight, performant, and easily integrated with the .NET Dependency Injection system. It leverages <strong>C# Source Generators</strong> for automatic handler registration at compile-time, eliminating the need for runtime reflection and improving application startup performance.
</p>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">Why Concordia?</h3>
<ul class="list-disc list-inside space-y-2 text-lg leading-relaxed">
<li><strong>An Open-Source Alternative</strong>: <strong>Concordia</strong> was created as an open-source alternative in response to other popular mediator libraries (like <code>MediatR</code>) transitioning to a paid licensing model. We believe core architectural patterns should remain freely accessible to the developer community.</li>
<li><strong>Lightweight and Minimal</strong>: Provides only the essential Mediator pattern functionalities, without unnecessary overhead.</li>
<li><strong>Optimized Performance</strong>: Thanks to <strong>Source Generators</strong>, handler discovery and registration happen entirely at compile-time, ensuring faster application startup and zero runtime reflection.</li>
<li><strong>Easy DI Integration</strong>: Integrates seamlessly with <code>Microsoft.Extensions.DependencyInjection</code>.</li>
<li><strong>Same MediatR Interfaces</strong>: Uses interfaces with identical signatures to <code>MediatR</code>, making migration or parallel adoption extremely straightforward.</li>
<li><strong>CQRS and Pub/Sub Patterns</strong>: Facilitates the implementation of Command Query Responsibility Segregation (CQRS) and Publisher/Subscriber principles, enhancing separation of concerns and code maintainability.</li>
</ul>
</section>
<hr class="my-12 border-slate-200">
<!-- Getting Started Section -->
<section id="getting-started" class="mb-12">
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Getting Started</h2>
<p class="text-lg leading-relaxed mb-4">
Getting started with <strong>Concordia</strong> involves a few straightforward steps to integrate the Mediator pattern into your .NET application.
</p>
<ol class="list-decimal list-inside space-y-2 text-lg leading-relaxed">
<li><strong>Define your Contracts</strong>: Create your requests, commands, and notifications by implementing <strong>Concordia</strong>'s interfaces (<code>IRequest<TResponse></code>, <code>IRequest</code>, <code>INotification</code>).</li>
<li><strong>Implement Handlers</strong>: Write the logic for your requests and notifications by implementing <code>IRequestHandler<TRequest, TResponse></code>, <code>IRequestHandler<TRequest></code>, or <code>INotificationHandler<TNotification></code>.</li>
<li><strong>Register with Dependency Injection</strong>: Integrate <strong>Concordia</strong> into your application's DI container. You can choose between compile-time registration (using the Source Generator) or runtime reflection-based registration (using the MediatR Compatibility layer).</li>
<li><strong>Use the Mediator</strong>: Inject <code>IMediator</code> or <code>ISender</code> into your services or controllers to dispatch requests and publish notifications.</li>
</ol>
</section>
<hr class="my-12 border-slate-200">
<!-- Installation Section -->
<section id="installation" class="mb-12">
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Installation</h2>
<p class="text-lg leading-relaxed mb-4">
<strong>Concordia</strong> is distributed via three NuGet packages, all currently at <strong>version <code>1.0.1</code></strong>:
</p>
<ul class="list-disc list-inside space-y-2 text-lg leading-relaxed mb-4">
<li><strong><code>Concordia.Core</code></strong>: Contains the interfaces (<code>IMediator</code>, <code>ISender</code>, <code>IRequest</code>, etc.), the <code>Mediator</code> implementation, and core DI extension methods.</li>
<li><strong><code>Concordia.Generator</code></strong>: Contains the C# Source Generator for compile-time handler registration.</li>
<li><strong><code>Concordia.MediatR</code></strong>: Provides a compatibility layer with MediatR's <code>AddMediator</code> extension method for runtime reflection-based handler registration, now using its own <code>ConcordiaMediatRServiceConfiguration</code>.</li>
</ul>
<p class="text-lg leading-relaxed mb-4">
To get started with <strong>Concordia</strong>, install the necessary packages in your application project (e.g., an ASP.NET Core project) using the .NET CLI. You will typically choose <strong>either <code>Concordia.Generator</code> OR <code>Concordia.MediatR</code></strong> based on your preference for handler registration.
</p>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">Option 1: Using the Source Generator (Recommended for New Projects)</h3>
<div class="code-block mb-6">
<pre><code class="language-bash">dotnet add package Concordia.Core --version 1.0.1
dotnet add package Concordia.Generator --version 1.0.1</code></pre>
</div>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">Option 2: Using the MediatR Compatibility Layer (For Migration or Reflection Preference)</h3>
<div class="code-block mb-6">
<pre><code class="language-bash">dotnet add package Concordia.Core --version 1.0.1
dotnet add package Concordia.MediatR --version 1.0.1</code></pre>
</div>
<p class="text-lg leading-relaxed">
Alternatively, you can install them via the NuGet Package Manager in Visual Studio.
</p>
</section>
<hr class="my-12 border-slate-200">
<!-- Usage Section -->
<section id="usage" class="mb-12">
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Usage</h2>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">1. Define Requests, Commands, and Notifications</h3>
<p class="text-lg leading-relaxed mb-4">
Your requests, commands, and notifications must implement the <code>Concordia.Contracts</code> interfaces.
</p>
<div class="code-block mb-6">
<pre><code class="language-csharp">// Request with response
using Concordia.Contracts;
namespace MyProject.Requests
{
public class GetProductByIdQuery : IRequest<ProductDto>
{
public int ProductId { get; set; }
}
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
// Fire-and-forget command
using Concordia.Contracts;
namespace MyProject.Commands
{
public class CreateProductCommand : IRequest
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
}
// Notification
using Concordia.Contracts;
namespace MyProject.Notifications
{
public class ProductCreatedNotification : INotification
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
}</code></pre>
</div>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">2. Define Handlers, Processors, and Behaviors</h3>
<p class="text-lg leading-relaxed mb-4">
Your handlers must implement <code>IRequestHandler</code> or <code>INotificationHandler</code>. Pre-processors implement <code>IRequestPreProcessor</code>, post-processors implement <code>IRequestPostProcessor</code>, and pipeline behaviors implement <code>IPipelineBehavior</code>.
</p>
<div class="code-block mb-6">
<pre><code class="language-csharp">// Handler for a request with response
using Concordia.Contracts;
using MyProject.Requests;
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Handlers
{
public class GetProductByIdQueryHandler : IRequestHandler<GetProductByIdQuery, ProductDto>
{
public Task<ProductDto> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
{
Console.WriteLine($"Handling GetProductByIdQuery for ProductId: {request.ProductId}");
var product = new ProductDto { Id = request.ProductId, Name = $"Product {request.ProductId}", Price = 10.50m };
return Task.FromResult(product);
}
}
}
// Handler for a fire-and-forget command
using Concordia.Contracts;
using MyProject.Commands;
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Handlers
{
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand>
{
public Task Handle(CreateProductCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"Creating product: {request.ProductName} with ID: {request.ProductId}");
return Task.CompletedTask;
}
}
}
// Notification Handler
using Concordia.Contracts;
using MyProject.Notifications;
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Handlers
{
public class SendEmailOnProductCreated : INotificationHandler<ProductCreatedNotification>
{
public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Sending email for new product: {notification.ProductName} (Id: {notification.ProductId})");
return Task.CompletedTask;
}
}
public class LogProductCreation : INotificationHandler<ProductCreatedNotification>
{
public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Logging product creation: {notification.ProductName} (Id: {notification.ProductId}) created at {DateTime.Now}");
return Task.CompletedTask;
}
}
}
// Example Request Pre-Processor
using Concordia.Contracts;
using MyProject.Requests; // Assuming your requests are here
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Processors
{
public class MyRequestLoggerPreProcessor : IRequestPreProcessor<GetProductByIdQuery>
{
public Task Process(GetProductByIdQuery request, CancellationToken cancellationToken)
{
Console.WriteLine($"Pre-processing GetProductByIdQuery for ProductId: {request.ProductId}");
return Task.CompletedTask;
}
}
}
// Example Request Post-Processor
using Concordia.Contracts;
using MyProject.Requests; // Assuming your requests are here
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Processors
{
public class MyResponseLoggerPostProcessor : IRequestPostProcessor<GetProductByIdQuery, ProductDto>
{
public Task Process(GetProductByIdQuery request, ProductDto response, CancellationToken cancellationToken)
{
Console.WriteLine($"Post-processing GetProductByIdQuery. Response: {response.Name}");
return Task.CompletedTask;
}
}
}
// Example Pipeline Behavior
using Concordia.Contracts;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace MyProject.Behaviors
{
public class TestLoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly List<string> _logs;
public TestLoggingBehavior(List<string> logs) { _logs = logs; }
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
_logs.Add($"Before {typeof(TRequest).Name}");
var response = await next();
_logs.Add($"After {typeof(TRequest).Name}");
return response;
}
}
}</code></pre>
</div>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">3. Choose Your Registration Method in <code>Program.cs</code></h3>
<p class="text-lg leading-relaxed mb-4">
You will use either the <strong>Source Generator method</strong> (recommended for new projects) or the MediatR Compatibility method (for easier migration).
</p>
<h4 class="text-xl font-semibold mb-3 text-slate-700">Option A: Using the Source Generator (Recommended)</h4>
<p class="text-lg leading-relaxed mb-4">
This method provides optimal startup performance by registering handlers at compile-time.
</p>
<h5 class="text-lg font-semibold mb-2 text-slate-700">i. Configure your <code>.csproj</code></h5>
<p class="text-lg leading-relaxed mb-4">
Add the <code>Concordia.Generator</code> as a <code>ProjectReference</code> to your application project's <code>.csproj</code> file. Ensure the <code>OutputItemType="Analyzer"</code> and <code>ReferenceOutputAssembly="false"</code> attributes are set. You can also customize the generated extension method's name using the <code>ConcordiaGeneratedMethodName</code> property.
</p>
<div class="code-block mb-6">
<pre><code class="language-xml"><Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Optional: Customize the generated extension method name -->
<ConcordiaGeneratedMethodName>AddMyConcordiaHandlers</ConcordiaGeneratedMethodName>
<!-- Optional: Customize the namespace for the generated class (defaults to project's RootNamespace) -->
<!-- <ConcordiaGeneratedNamespace>MyProject.Generated</ConcordiaGeneratedNamespace> -->
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="PathToYour\Concordia.Core\Concordia.Core.csproj" />
<ProjectReference Include="PathToYour\Concordia.Generator\Concordia.Generator.csproj"
OutputItemType="Analyzer" ReferenceOutputAssembly="false" />
</ItemGroup>
<!-- Ensure your Request, Handler, Processor, and Behavior files are included in the project -->
<ItemGroup>
<Compile Include="Requests\MySimpleQuery.cs" />
<Compile Include="Handlers\MySimpleQueryHandler.cs" />
<Compile Include="Processors\MyRequestLoggerPreProcessor.cs" />
<Compile Include="Processors\MyResponseLoggerPostProcessor.cs" />
<Compile Include="Behaviors\TestLoggingBehavior.cs" />
<!-- ... other handlers, processors, behaviors ... -->
</ItemGroup>
</Project></code></pre>
</div>
<h5 class="text-lg font-semibold mb-2 text-slate-700">ii. Register services in <code>Program.cs</code></h5>
<p class="text-lg leading-relaxed mb-4">
After configuring your <code>.csproj</code>, the Source Generator will automatically generate an extension method (e.g., <code>AddMyConcordiaHandlers</code>) that registers all your handlers, processors, and behaviors. Call this method in your <code>Program.cs</code> after registering Concordia's core services.
</p>
<div class="code-block mb-6">
<pre><code class="language-csharp">using Concordia; // Required for IMediator, ISender
using Concordia.DependencyInjection; // For AddConcordiaCoreServices
using Microsoft.AspNetCore.Mvc;
using MyProject.Web; // Example: Namespace where ConcordiaGeneratedRegistrations is generated
var builder = WebApplication.CreateBuilder(args);
// 1. Register Concordia's core services (IMediator, ISender).
// You can use the parameterless method for the default publisher, or:
builder.Services.AddConcordiaCoreServices<Concordia.ForeachAwaitPublisher>(); // Example: Explicitly register the default publisher
// Or, if you have a custom publisher:
// builder.Services.AddConcordiaCoreServices<MyCustomNotificationPublisher>(); // Example: Register your custom publisher
// 2. Register your specific handlers and pipeline behaviors discovered by the generator.
// The method name will depend on your your .csproj configuration (e.g., AddMyConcordiaHandlers).
builder.Services.AddMyConcordiaHandlers(); // Example with a custom name
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
// Example Controller for usage (remains unchanged)
namespace Concordia.Examples.Web.Controllers
{
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private readonly IMediator _mediator;
private readonly ISender _sender;
public ProductsController(IMediator mediator, ISender sender)
{
_mediator = mediator;
_sender = sender;
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var query = new GetProductByIdQuery { ProductId = id };
var product = await _sender.Send(query);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public async Task<IActionResult> CreateProduct([FromBody] CreateProductCommand command)
{
await _sender.Send(command);
var notification = new ProductCreatedNotification
{
ProductId = command.ProductId,
ProductName = command.ProductName
};
await _mediator.Publish(notification);
return CreatedAtAction(nameof(Get), new { id = command.ProductId }, null);
}
}
// Examples of requests, commands, notifications and handlers for the web project
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class GetProductByIdQuery : IRequest<ProductDto>
{
public Task<ProductDto> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
{
Console.WriteLine($"Handling GetProductByIdQuery for ProductId: {request.ProductId}");
var product = new ProductDto { Id = request.ProductId, Name = $"Product {request.ProductId}", Price = 10.50m };
return Task.FromResult(product);
}
}
public class CreateProductCommand : IRequest
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand>
{
public Task Handle(CreateProductCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"Creating product: {request.ProductName} with ID: {request.ProductId}");
return Task.CompletedTask;
}
}
public class ProductCreatedNotification : INotification
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
public class SendEmailOnProductCreated : INotificationHandler<ProductCreatedNotification>
{
public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Sending email for new product: {notification.ProductName} (Id: {notification.ProductId})");
return Task.CompletedTask;
}
}
public class LogProductCreation : INotificationHandler<ProductCreatedNotification>
{
public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Logging product creation: {notification.ProductName} (Id: {notification.ProductId}) created at {DateTime.Now}");
return Task.CompletedTask;
}
}
}</code></pre>
</div>
<h4 class="text-xl font-semibold mb-3 text-slate-700">Option B: Using the MediatR Compatibility Layer</h4>
<p class="text-lg leading-relaxed mb-4">
This method uses runtime reflection to register handlers, offering a familiar setup for those migrating from <code>MediatR</code>.
</p>
<div class="code-block mb-6">
<pre><code class="language-csharp">using Concordia; // Required for IMediator, ISender
using Concordia.MediatR; // NEW: Namespace for the AddMediator extension method
using System.Reflection; // Required for Assembly.GetExecutingAssembly()
using Microsoft.Extensions.DependencyInjection; // Required for ServiceLifetime
var builder = WebApplication.CreateBuilder(args);
// Register Concordia and all handlers using the reflection-based AddMediator method.
// This will scan the specified assemblies (e.g., the current executing assembly)
// to find and register all handlers and pipeline behaviors.
builder.Services.AddMediator(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
// Example: Register all services as Scoped
cfg.Lifetime = ServiceLifetime.Scoped;
// Example: Register a custom notification publisher
// cfg.NotificationPublisherType = typeof(MyCustomNotificationPublisher);
// Example: Explicitly add a pre-processor
// cfg.AddRequestPreProcessor<MyCustomPreProcessor>();
// Example: Explicitly add a post-processor
// cfg.AddRequestPostProcessor<MyCustomPostProcessor>();
// Example: Explicitly add a stream behavior
// cfg.AddStreamBehavior<MyCustomStreamBehavior>();
});
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
// Example Controller for usage (remains unchanged)
namespace Concordia.Examples.Web.Controllers
{
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private readonly IMediator _mediator;
private readonly ISender _sender;
public ProductsController(IMediator mediator, ISender sender)
{
_mediator = mediator;
_sender = sender;
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
var query = new GetProductByIdQuery { ProductId = id };
var product = await _sender.Send(query);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
[HttpPost]
public async Task<IActionResult> CreateProduct([FromBody] CreateProductCommand command)
{
await _sender.Send(command);
var notification = new ProductCreatedNotification
{
ProductId = command.ProductId,
ProductName = command.ProductName
};
await _mediator.Publish(notification);
return CreatedAtAction(nameof(Get), new { id = command.ProductId }, null);
}
}
// Examples of requests, commands, notifications and handlers for the web project
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class GetProductByIdQuery : IRequest<ProductDto>
{
public Task<ProductDto> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
{
Console.WriteLine($"Handling GetProductByIdQuery for ProductId: {request.ProductId}");
var product = new ProductDto { Id = request.ProductId, Name = $"Product {request.ProductId}", Price = 10.50m };
return Task.FromResult(product);
}
}
public class CreateProductCommand : IRequest
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
public class CreateProductCommandHandler : IRequestHandler<CreateProductCommand>
{
public Task Handle(CreateProductCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"Creating product: {request.ProductName} with ID: {request.ProductId}");
return Task.CompletedTask;
}
}
public class ProductCreatedNotification : INotification
{
public int ProductId { get; set; }
public string ProductName { get; set; }
}
public class SendEmailOnProductCreated : INotificationHandler<ProductCreatedNotification>
{
public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Sending email for new product: {notification.ProductName} (Id: {notification.ProductId})");
return Task.CompletedTask;
}
}
public class LogProductCreation : INotificationHandler<ProductCreatedNotification>
{
public Task Handle(ProductCreatedNotification notification, CancellationToken cancellationToken)
{
Console.WriteLine($"Logging product creation: {notification.ProductName} (Id: {notification.ProductId}) created at {DateTime.Now}");
return Task.CompletedTask;
}
}
}</code></pre>
</div>
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Migration Guide from <code>MediatR</code></h2>
<p class="text-lg leading-relaxed mb-4">
If you are migrating an existing project from <code>MediatR</code> to <code>Concordia</code>, the process is extremely simple thanks to the identical interfaces and patterns.
</p>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">1. Update NuGet Packages</h3>
<p class="text-lg leading-relaxed mb-4">
Remove the <code>MediatR</code> package and install the <code>Concordia</code> packages:
</p>
<div class="code-block mb-6">
<pre><code class="language-bash">dotnet remove package MediatR
dotnet remove package MediatR.Extensions.Microsoft.DependencyInjection # If present
dotnet add package Concordia.Core --version 1.0.1
dotnet add package Concordia.MediatR --version 1.0.1</code></pre>
</div>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">2. Update Namespaces</h3>
<p class="text-lg leading-relaxed mb-4">
Change namespaces from <code>MediatR</code> to <code>Concordia</code> and <code>Concordia.Contracts</code> where necessary.
</p>
<ul class="list-disc list-inside space-y-2 text-lg leading-relaxed mb-4">
<li><strong>Interfaces</strong>:
<ul class="list-circle list-inside ml-4">
<li><code>MediatR.IRequest<TResponse></code> becomes <code>Concordia.Contracts.IRequest<TResponse></code></li>
<li><code>MediatR.IRequest</code> becomes <code>Concordia.Contracts.IRequest</code></li>
<li><code>MediatR.IRequestHandler<TRequest, TResponse></code> becomes <code>Concordia.Contracts.IRequestHandler<TRequest, TResponse></code></li>
<li><code>MediatR.IRequestHandler<TRequest></code> becomes <code>Concordia.Contracts.IRequestHandler<TRequest></code></li>
<li><code>MediatR.INotification</code> becomes <code>Concordia.Contracts.INotification</code></li>
<li><code>MediatR.INotificationHandler<TNotification></code> becomes <code>Concordia.Contracts.INotificationHandler<TNotification></code></li>
<li><code>MediatR.IPipelineBehavior<TRequest, TResponse></code> becomes <code>Concordia.Contracts.IPipelineBehavior<TRequest, TResponse></code></li>
<li><code>MediatR.IRequestPreProcessor<TRequest></code> becomes <code>Concordia.Contracts.IRequestPreProcessor<TRequest></code></li>
<li><code>MediatR.IRequestPostProcessor<TRequest, TResponse></code> becomes <code>Concordia.Contracts.IRequestPostProcessor<TRequest, TResponse></code></li>
<li><code>MediatR.INotificationPublisher</code> becomes <code>Concordia.Contracts.INotificationPublisher</code></li>
</ul>
</li>
<li><strong>Mediator Implementation</strong>:
<ul class="list-circle list-inside ml-4">
<li><code>MediatR.IMediator</code> becomes <code>Concordia.IMediator</code></li>
<li><code>MediatR.ISender</code> becomes <code>Concordia.ISender</code></li>
<li><code>MediatR.Mediator</code> becomes <code>Concordia.Mediator</code></li>
</ul>
</li>
</ul>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">3. Update Service Registration in <code>Program.cs</code> (or <code>Startup.cs</code>)</h3>
<p class="text-lg leading-relaxed mb-4">
Replace the <code>AddMediatR</code> extension method with <strong>Concordia</strong>'s <code>AddMediator</code>.
</p>
<h4 class="text-xl font-semibold mb-3 text-slate-700">Before (MediatR):</h4>
<div class="code-block mb-6">
<pre><code class="language-csharp">using MediatR;
using MediatR.Extensions.Microsoft.DependencyInjection; // If present
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
// Other MediatR configurations
});</code></pre>
</div>
<h4 class="text-xl font-semibold mb-3 text-slate-700">After (Concordia.MediatR):</h4>
<div class="code-block mb-6">
<pre><code class="language-csharp">using Concordia; // For IMediator, ISender
using Concordia.MediatR; // For the AddMediator extension method
using System.Reflection;
using Microsoft.Extensions.DependencyInjection; // For ServiceLifetime
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMediator(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
// Configuration options are similar to MediatR, but use the ConcordiaMediatRServiceConfiguration class
cfg.Lifetime = ServiceLifetime.Scoped; // Example
// cfg.NotificationPublisherType = typeof(MyCustomNotificationPublisher); // Example
// cfg.AddOpenBehavior(typeof(MyCustomPipelineBehavior<,>)); // Example
// cfg.AddRequestPreProcessor<MyCustomPreProcessor>(); // Example
// cfg.AddRequestPostProcessor<MyCustomPostProcessor>(); // Example
// cfg.AddStreamBehavior<MyCustomStreamBehavior>(); // Example
});</code></pre>
</div>
<h3 class="text-2xl font-semibold mb-4 text-slate-700">4. Verify and Test</h3>
<p class="text-lg leading-relaxed mb-4">
Rebuild your project and run your tests. Given the interface parity, most of your existing code should function without significant changes.
</p>
</section>
<hr class="my-12 border-slate-200">
<!-- Source Code Section -->
<section id="source-code" class="mb-12">
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Source Code</h2>
<p class="text-lg leading-relaxed mb-4">
The complete source code for the <strong>Concordia</strong> library is available on GitHub. Feel free to explore, contribute, or fork the repository.
</p>
<div class="flex justify-center">
<a href="https://github.com/lucafabbri/Concordia" target="_blank" class="inline-block bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-3 px-6 rounded-lg shadow-lg transition-colors duration-300">
View on GitHub
</a>
</div>
</section>
<!-- Contributing Section -->
<section id="contributing" class="mb-12">
<h2 class="text-4xl font-extrabold mb-6 text-indigo-700 section-title">Contributing</h2>
<p class="text-lg leading-relaxed mb-4">
We welcome contributions from the community! Please make sure to read our
<a href="CONTRIBUTING.md" class="text-indigo-600 hover:underline">Contributing Guidelines</a>
and our <a href="CODE_OF_CONDUCT.md" class="text-indigo-600 hover:underline">Code of Conduct</a>
before getting started.
</p>
<p class="text-lg leading-relaxed">
Your contributions help us improve and grow Concordia. Thank you for your support!
</p>
</section>
</main>
</div>
<!-- Footer -->
<footer class="page-footer bg-slate-800 text-slate-200 p-6 text-center rounded-t-lg">
<p>© 2025 Concordia Library. All rights reserved.</p>
<p class="text-sm mt-2">Built with ❤️ and .NET</p>
</footer>
<!-- Highlight.js for syntax highlighting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- Optional: Include specific languages if you don't need all -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/csharp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/bash.min.js"></script>
<script>
// Initialize Highlight.js after the DOM is loaded
document.addEventListener('DOMContentLoaded', (event) => {
hljs.highlightAll();
});
</script>
</body>
</html>