Skip to content

Commit 380d06a

Browse files
author
giordanol
committed
Added demo projrct for DI
1 parent 8cc1fed commit 380d06a

File tree

7 files changed

+165
-1
lines changed

7 files changed

+165
-1
lines changed

Blumchen.sln

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "demo", "demo", "{A4044484-F
4545
EndProject
4646
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Blumchen.DependencyInjection", "src\Blumchen.DependencyInjection\Blumchen.DependencyInjection.csproj", "{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}"
4747
EndProject
48+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SubscriberWorker", "src\SubscriberWorker\SubscriberWorker.csproj", "{DB58DB36-0366-4ABA-BC06-FCA9BB10EB92}"
49+
EndProject
4850
Global
4951
GlobalSection(SolutionConfigurationPlatforms) = preSolution
5052
Debug|Any CPU = Debug|Any CPU
@@ -75,6 +77,10 @@ Global
7577
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Debug|Any CPU.Build.0 = Debug|Any CPU
7678
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Release|Any CPU.ActiveCfg = Release|Any CPU
7779
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Release|Any CPU.Build.0 = Release|Any CPU
80+
{DB58DB36-0366-4ABA-BC06-FCA9BB10EB92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
81+
{DB58DB36-0366-4ABA-BC06-FCA9BB10EB92}.Debug|Any CPU.Build.0 = Debug|Any CPU
82+
{DB58DB36-0366-4ABA-BC06-FCA9BB10EB92}.Release|Any CPU.ActiveCfg = Release|Any CPU
83+
{DB58DB36-0366-4ABA-BC06-FCA9BB10EB92}.Release|Any CPU.Build.0 = Release|Any CPU
7884
EndGlobalSection
7985
GlobalSection(SolutionProperties) = preSolution
8086
HideSolutionNode = FALSE
@@ -85,6 +91,7 @@ Global
8591
{F81E2D5B-FC59-4396-A911-56BE65E4FE80} = {A4044484-FE08-4399-8239-14AABFA30AD7}
8692
{C050E9E8-3FB6-4581-953F-31826E385FB4} = {CD59A1A0-F40D-4047-87A3-66C0F1519FA5}
8793
{8AAAA344-B5FD-48D9-B2BA-379E374448D4} = {CD59A1A0-F40D-4047-87A3-66C0F1519FA5}
94+
{DB58DB36-0366-4ABA-BC06-FCA9BB10EB92} = {A4044484-FE08-4399-8239-14AABFA30AD7}
8895
EndGlobalSection
8996
GlobalSection(ExtensibilityGlobals) = postSolution
9097
SolutionGuid = {9A868C51-0460-4700-AF33-E1A921192614}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Main logic is placed in [EventsSubscription](./src/Blumchen/Subscriptions/Subscr
1818
```shell
1919
docker-compose up
2020
```
21-
2. Run(order doesn't matter) Publisher and Subscriber apps, under 'demo' folder, from vs-studio, and follow Publisher instructions.
21+
2. Run(order doesn't matter) Publisher and (Subscriber or SubscriberWorker) apps, under 'demo' folder, from vs-studio, and follow Publisher instructions.
2222

2323
## Testing (against default docker instance)
2424

src/SubscriberWorker/Contracts.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System.Text.Json.Serialization;
2+
using Blumchen.Serialization;
3+
4+
namespace SubscriberWorker
5+
{
6+
[MessageUrn("user-created:v1")]
7+
public record UserCreatedContract(
8+
Guid Id,
9+
string Name
10+
);
11+
12+
[MessageUrn("user-deleted:v1")]
13+
public record UserDeletedContract(
14+
Guid Id,
15+
string Name
16+
);
17+
18+
[JsonSourceGenerationOptions(WriteIndented = true)]
19+
[JsonSerializable(typeof(UserCreatedContract))]
20+
[JsonSerializable(typeof(UserDeletedContract))]
21+
internal partial class SourceGenerationContext: JsonSerializerContext;
22+
}

src/SubscriberWorker/Handler.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using Blumchen.Subscriptions;
2+
using Microsoft.Extensions.Logging;
3+
#pragma warning disable CS9113 // Parameter is unread.
4+
5+
namespace SubscriberWorker;
6+
7+
8+
public class Handler<T>(ILoggerFactory loggerFactory): IHandler<T> where T : class
9+
{
10+
private readonly ILogger _logger = loggerFactory.CreateLogger<Handler<T>>();
11+
private Task ReportSuccess(int count)
12+
{
13+
if(_logger.IsEnabled(LogLevel.Debug))
14+
_logger.LogDebug($"Read #{count} messages {typeof(T).FullName}");
15+
return Task.CompletedTask;
16+
}
17+
18+
private int _counter;
19+
private int _completed;
20+
public Task Handle(T value)
21+
=> Interlocked.Increment(ref _counter) % 10 == 0
22+
//Simulating some exception on out of process dependencies
23+
? Task.FromException(new Exception($"Error on publishing {nameof(T)}"))
24+
: ReportSuccess(Interlocked.Increment(ref _completed));
25+
}

src/SubscriberWorker/Program.cs

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
using System.Text.Json.Serialization;
2+
using Blumchen.Configuration;
3+
using Blumchen.Serialization;
4+
using Blumchen.Subscriptions;
5+
using Blumchen.Workers;
6+
using Commons;
7+
using Microsoft.Extensions.DependencyInjection;
8+
using Microsoft.Extensions.Hosting;
9+
using Microsoft.Extensions.Logging;
10+
using Polly.Retry;
11+
using Polly;
12+
using SubscriberWorker;
13+
14+
15+
#pragma warning disable CS8601 // Possible null reference assignment.
16+
Console.Title = typeof(Program).Assembly.GetName().Name;
17+
#pragma warning restore CS8601 // Possible null reference assignment.
18+
19+
20+
21+
AppDomain.CurrentDomain.UnhandledException += (_, e) => Console.Out.WriteLine(e.ExceptionObject.ToString());
22+
TaskScheduler.UnobservedTaskException += (_, e) => Console.Out.WriteLine(e.Exception.ToString());
23+
24+
var cancellationTokenSource = new CancellationTokenSource();
25+
var builder = Host.CreateApplicationBuilder(args);
26+
27+
builder.Services
28+
.AddBlumchen<SubscriberWorker<UserCreatedContract>, UserCreatedContract>()
29+
.AddSingleton<IHandler<UserCreatedContract>, Handler<UserCreatedContract>>()
30+
.AddBlumchen<SubscriberWorker<UserDeletedContract>, UserDeletedContract>()
31+
.AddSingleton<IHandler<UserDeletedContract>, Handler<UserDeletedContract>>()
32+
33+
.AddSingleton<INamingPolicy, AttributeNamingPolicy>()
34+
.AddSingleton<IErrorProcessor, ConsoleOutErrorProcessor>()
35+
.AddSingleton<JsonSerializerContext, SourceGenerationContext>()
36+
.AddSingleton(new DatabaseOptions(Settings.ConnectionString))
37+
.AddResiliencePipeline("default",(pipelineBuilder,context) =>
38+
pipelineBuilder
39+
.AddRetry(new RetryStrategyOptions
40+
{
41+
BackoffType = DelayBackoffType.Constant,
42+
Delay = TimeSpan.FromSeconds(5),
43+
MaxRetryAttempts = int.MaxValue
44+
}).Build())
45+
.AddLogging(loggingBuilder =>
46+
{
47+
loggingBuilder
48+
.AddFilter("Microsoft", LogLevel.Warning)
49+
.AddFilter("System", LogLevel.Warning)
50+
.AddFilter("Npgsql", LogLevel.Information)
51+
.AddFilter("Blumchen", LogLevel.Debug)
52+
.AddFilter("SubscriberWorker", LogLevel.Debug)
53+
.AddSimpleConsole();
54+
});
55+
56+
await builder
57+
.Build()
58+
.RunAsync(cancellationTokenSource.Token)
59+
.ConfigureAwait(false);
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System.Text.Json.Serialization;
2+
using Blumchen.Configuration;
3+
using Blumchen.Serialization;
4+
using Blumchen.Subscriptions;
5+
using Blumchen.Subscriptions.Management;
6+
using Blumchen.Workers;
7+
using Microsoft.Extensions.Logging;
8+
using Polly.Registry;
9+
// ReSharper disable ClassNeverInstantiated.Global
10+
11+
namespace SubscriberWorker;
12+
public class SubscriberWorker<T>(
13+
DatabaseOptions databaseOptions,
14+
IHandler<T> handler,
15+
JsonSerializerContext jsonSerializerContext,
16+
ResiliencePipelineProvider<string> pipelineProvider,
17+
INamingPolicy namingPolicy,
18+
IErrorProcessor errorProcessor,
19+
ILoggerFactory loggerFactory
20+
): Worker<T>(databaseOptions
21+
, handler
22+
, jsonSerializerContext
23+
, errorProcessor
24+
, pipelineProvider.GetPipeline("default")
25+
, namingPolicy
26+
, new PublicationManagement.PublicationSetupOptions($"{typeof(T).Name}_pub")
27+
, new ReplicationSlotManagement.ReplicationSlotSetupOptions($"{typeof(T).Name}_slot")
28+
, loggerFactory) where T : class;
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
<PublishAot>true</PublishAot>
9+
<InvariantGlobalization>true</InvariantGlobalization>
10+
<IsPackable>false</IsPackable>
11+
</PropertyGroup>
12+
13+
<ItemGroup>
14+
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
15+
<PackageReference Include="Polly.Extensions" Version="8.4.1" />
16+
</ItemGroup>
17+
18+
<ItemGroup>
19+
<ProjectReference Include="..\Blumchen.DependencyInjection\Blumchen.DependencyInjection.csproj" />
20+
<ProjectReference Include="..\Commons\Commons.csproj" />
21+
</ItemGroup>
22+
23+
</Project>

0 commit comments

Comments
 (0)