Skip to content

Commit

Permalink
Added DependencyIbjection project
Browse files Browse the repository at this point in the history
  • Loading branch information
lsfera committed Jul 5, 2024
1 parent b024c6f commit 8cc1fed
Show file tree
Hide file tree
Showing 5 changed files with 134 additions and 0 deletions.
6 changes: 6 additions & 0 deletions Blumchen.sln
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "postgres", "postgres", "{8A
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "demo", "demo", "{A4044484-FE08-4399-8239-14AABFA30AD7}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Blumchen.DependencyInjection", "src\Blumchen.DependencyInjection\Blumchen.DependencyInjection.csproj", "{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -69,6 +71,10 @@ Global
{2BBDA071-FB1C-4D62-A954-B22EA6B1C738}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2BBDA071-FB1C-4D62-A954-B22EA6B1C738}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2BBDA071-FB1C-4D62-A954-B22EA6B1C738}.Release|Any CPU.Build.0 = Release|Any CPU
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A07167E3-4CF7-40EF-8E55-A37A0F57B89D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<VersionPrefix>0.1.0</VersionPrefix>
<TargetFramework>net8.0</TargetFramework>
<GenerateAssemblyTitleAttribute>true</GenerateAssemblyTitleAttribute>
<GenerateAssemblyDescriptionAttribute>true</GenerateAssemblyDescriptionAttribute>
<GenerateAssemblyProductAttribute>true</GenerateAssemblyProductAttribute>
<GenerateAssemblyCopyrightAttribute>false</GenerateAssemblyCopyrightAttribute>
<GenerateAssemblyVersionAttribute>true</GenerateAssemblyVersionAttribute>
<GenerateAssemblyFileVersionAttribute>true</GenerateAssemblyFileVersionAttribute>
<GenerateAssemblyInformationalVersionAttribute>true</GenerateAssemblyInformationalVersionAttribute>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<LangVersion>12.0</LangVersion>
<Authors>Oskar Dudycz</Authors>
<!-- <PackageIconUrl>https://github.com/event-driven-io/Blumchen/content/images/emblem.png</PackageIconUrl>-->
<PackageProjectUrl>https://github.com/event-driven-io/Blumchen</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryUrl>https://github.com/event-driven-io/Blumchen.git</RepositoryUrl>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<Product>Blumchen</Product>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<RootNamespace>Blumchen</RootNamespace>
<PublishAot>true</PublishAot>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<NoWarn>1591</NoWarn>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<NoWarn>1591</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageReference Include="Polly" Version="8.4.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Blumchen\Blumchen.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
namespace Blumchen.Configuration;
public record DatabaseOptions(string ConnectionString);
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.Extensions.DependencyInjection;
#pragma warning disable IL2091

namespace Blumchen.Workers;

public static class ServiceCollectionExtensions
{
public static IServiceCollection AddBlumchen<T,TU>(this IServiceCollection service, T? instance = default)
where T : Worker<TU> where TU : class =>
instance is null
? service.AddHostedService<T>()
: service.AddHostedService(_=>instance);
}
64 changes: 64 additions & 0 deletions src/Blumchen.DependencyInjection/Workers/Worker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System.Collections.Concurrent;
using System.Text.Json.Serialization;
using Blumchen.Configuration;
using Blumchen.Serialization;
using Blumchen.Subscriptions;
using Blumchen.Subscriptions.Management;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Polly;


namespace Blumchen.Workers;

public abstract class Worker<T>(
DatabaseOptions databaseOptions,
IHandler<T> handler,
JsonSerializerContext jsonSerializerContext,
IErrorProcessor errorProcessor,
ResiliencePipeline pipeline,
INamingPolicy namingPolicy,
PublicationManagement.PublicationSetupOptions publicationSetupOptions,
ReplicationSlotManagement.ReplicationSlotSetupOptions replicationSlotSetupOptions,
ILoggerFactory loggerFactory): BackgroundService where T : class
{
private readonly ILogger<Worker<T>> _logger = loggerFactory.CreateLogger<Worker<T>>();
private string WorkerName { get; } = $"{nameof(Worker<T>)}<{typeof(T).Name}>";
private static readonly ConcurrentDictionary<string, Action<ILogger, string, object[]>> _actions = new(StringComparer.OrdinalIgnoreCase);
private static void Notify(ILogger logger, LogLevel level, string template, params object[] parameters)
{
static Action<ILogger, string, object[]> LoggerAction(LogLevel ll, bool enabled) =>
(ll, enabled) switch
{
(LogLevel.Information, true) => (logger, template, parameters) => logger.LogInformation(template, parameters),
(LogLevel.Debug, true) => (logger, template, parameters) => logger.LogDebug(template, parameters),
(_, _) => (_, __, ___) => { }
};
_actions.GetOrAdd(template,s => LoggerAction(level, logger.IsEnabled(level)))(logger, template, parameters);
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await pipeline.ExecuteAsync(async token =>
{
await using var subscription = new Subscription();
await using var cursor = subscription.Subscribe(builder =>
builder
.ConnectionString(databaseOptions.ConnectionString)
.WithErrorProcessor(errorProcessor)
.Handles<T, IHandler<T>>(handler)
.NamingPolicy(namingPolicy)
.JsonContext(jsonSerializerContext)
.WithPublicationOptions(publicationSetupOptions)
.WithReplicationOptions(replicationSlotSetupOptions)
, ct: token, loggerFactory: loggerFactory).GetAsyncEnumerator(token);
Notify(_logger, LogLevel.Information,"{WorkerName} started", WorkerName);
while (await cursor.MoveNextAsync().ConfigureAwait(false) && !token.IsCancellationRequested)
Notify(_logger, LogLevel.Debug, "{cursor.Current} processed", cursor.Current);

}, stoppingToken).ConfigureAwait(false);
Notify(_logger, LogLevel.Information, "{WorkerName} stopped", WorkerName);
return;
}

}

0 comments on commit 8cc1fed

Please sign in to comment.