Skip to content

Commit f984ed9

Browse files
authored
Added cookbook page for publish-subscribe pattern (#7)
1 parent f638615 commit f984ed9

File tree

1 file changed

+36
-0
lines changed
  • src/routes/docs/[...6]cookbook/[...7]pub-sub

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
title: Publish-Subscribe pattern
3+
description: Cookbook example showing how to implement the publish-subscribe pattern
4+
---
5+
6+
# {$frontmatter.title}
7+
8+
If you are coming from other popular mediator libraries, you may be looking for a way to implement the
9+
[publish-subscribe pattern](https://learn.microsoft.com/en-us/azure/architecture/patterns/publisher-subscriber)
10+
with Immediate.Handlers. A common use case is implementing domain events.
11+
12+
Immediate.Handlers fully supports this pattern, but it intentionally does not provide a built-in `Publisher`
13+
abstraction. Maintaining an opinionated publish-subscribe implementation is out of scope and would limit
14+
the flexibility required by different projects.
15+
16+
An example is provided here of a simple `Publisher` which works for many cases.
17+
18+
```cs
19+
public sealed class Publisher<TNotification>(
20+
IServiceProvider serviceProvider
21+
)
22+
{
23+
public async ValueTask Publish(TNotification notification)
24+
{
25+
foreach (var handler in serviceProvider.GetServices<IHandler<TNotification, ValueTuple>>())
26+
{
27+
await handler.Handle(notification);
28+
}
29+
}
30+
}
31+
```
32+
33+
Finally, this implementation can simply be registered as singleton service:
34+
```cs
35+
services.AddSingleton(typeof(Publisher<>));
36+
```

0 commit comments

Comments
 (0)