Skip to content

Commit

Permalink
Add Example05
Browse files Browse the repository at this point in the history
  • Loading branch information
aimenux committed Dec 6, 2024
1 parent a21ad01 commit cef81c2
Show file tree
Hide file tree
Showing 19 changed files with 247 additions and 12 deletions.
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
<PackageVersion Include="MassTransit.Azure.ServiceBus.Core" Version="8.3.3" />
<PackageVersion Include="Microsoft.Extensions.Hosting" Version="8.0.1" />
<PackageVersion Include="System.Text.Json" Version="8.0.5" />
<PackageVersion Include="WolverineFx.AzureServiceBus" Version="3.4.0" />
</ItemGroup>
</Project>
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,7 @@ Playing with service bus
>
> :four: `Example04` : use worker template with [MassTransit](https://masstransit-project.com)
>
> :five: `Example05` : use worker template with [Wolverine](https://wolverinefx.net)
>
**`Tools`** : net 8.0, servicebus, masstransit
**`Tools`** : net 8.0, servicebus, masstransit, wolverine
7 changes: 7 additions & 0 deletions ServiceBusDemo.sln
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example02", "src\Example02\
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example04", "src\Example04\Example04.csproj", "{EFA5CB6E-D00C-450F-98BC-0A94B59A7AD4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example05", "src\Example05\Example05.csproj", "{18585800-512B-4E0B-88A5-C9556465F17E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -49,11 +51,16 @@ Global
{EFA5CB6E-D00C-450F-98BC-0A94B59A7AD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EFA5CB6E-D00C-450F-98BC-0A94B59A7AD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EFA5CB6E-D00C-450F-98BC-0A94B59A7AD4}.Release|Any CPU.Build.0 = Release|Any CPU
{18585800-512B-4E0B-88A5-C9556465F17E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{18585800-512B-4E0B-88A5-C9556465F17E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{18585800-512B-4E0B-88A5-C9556465F17E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{18585800-512B-4E0B-88A5-C9556465F17E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{1F1CAFDA-2CE5-4248-B437-512552BFF221} = {675A9474-CB75-4BB9-96ED-7A4F6DBF6DD8}
{35DB9CC1-DC4E-4891-A1C1-12A2BBA47E08} = {675A9474-CB75-4BB9-96ED-7A4F6DBF6DD8}
{C5AA6BD9-2F7B-4F7C-AE2E-3BAE12B34E29} = {675A9474-CB75-4BB9-96ED-7A4F6DBF6DD8}
{EFA5CB6E-D00C-450F-98BC-0A94B59A7AD4} = {675A9474-CB75-4BB9-96ED-7A4F6DBF6DD8}
{18585800-512B-4E0B-88A5-C9556465F17E} = {675A9474-CB75-4BB9-96ED-7A4F6DBF6DD8}
EndGlobalSection
EndGlobal
6 changes: 3 additions & 3 deletions src/Example01/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,15 @@ private static void AddSettings(this HostApplicationBuilder builder)

private static void AddServiceBus(this HostApplicationBuilder builder)
{
builder.Services.AddHostedService<MessageConsumer>();
builder.Services.AddHostedService<MessageProducer>();

builder.Services.AddSingleton(sp =>
{
var settings = sp.GetRequiredService<IOptions<Settings>>().Value;
var client = GetServiceBusClient(settings);
return client;
});

builder.Services.AddHostedService<MessageConsumer>();
builder.Services.AddHostedService<MessageProducer>();
}

private static ServiceBusClient GetServiceBusClient(Settings settings)
Expand Down
6 changes: 3 additions & 3 deletions src/Example02/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ private static void AddSettings(this HostApplicationBuilder builder)

private static void AddServiceBus(this HostApplicationBuilder builder)
{
builder.Services.AddHostedService<MessageConsumer>();
builder.Services.AddHostedService<MessageProducer>();

builder.Services.AddSingleton(sp =>
{
var settings = sp.GetRequiredService<IOptions<Settings>>().Value;
Expand All @@ -40,6 +37,9 @@ private static void AddServiceBus(this HostApplicationBuilder builder)
var sender = GetServiceBusSender(client, settings);
return sender;
});

builder.Services.AddHostedService<MessageConsumer>();
builder.Services.AddHostedService<MessageProducer>();
}

private static ServiceBusClient GetServiceBusClient(Settings settings)
Expand Down
6 changes: 3 additions & 3 deletions src/Example03/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@ private static void AddSettings(this HostApplicationBuilder builder)

private static void AddServiceBus(this HostApplicationBuilder builder)
{
builder.Services.AddHostedService<MessageConsumer>();
builder.Services.AddHostedService<MessageProducer>();

builder.Services.AddSingleton(sp =>
{
var settings = sp.GetRequiredService<IOptions<Settings>>().Value;
Expand All @@ -39,6 +36,9 @@ private static void AddServiceBus(this HostApplicationBuilder builder)
var processor = GetServiceBusProcessor(client, settings);
return processor;
});

builder.Services.AddHostedService<MessageConsumer>();
builder.Services.AddHostedService<MessageProducer>();
}

private static ServiceBusClient GetServiceBusClient(Settings settings)
Expand Down
4 changes: 2 additions & 2 deletions src/Example04/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@ private static void AddServiceBus(this HostApplicationBuilder builder)
{
var hostSettings = builder.Configuration.GetHostSettings();

builder.Services.AddHostedService<MessageProducer>();

builder.Services.AddMassTransit(configure =>
{
configure.SetKebabCaseEndpointNameFormatter();
Expand All @@ -37,6 +35,8 @@ private static void AddServiceBus(this HostApplicationBuilder builder)
cfg.ConfigureEndpoints(context);
});
});

builder.Services.AddHostedService<MessageProducer>();
}

private static HostSettings GetHostSettings(this ConfigurationManager configuration)
Expand Down
11 changes: 11 additions & 0 deletions src/Example05/Configuration/Settings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Example05.Configuration;

public sealed record Settings
{
public const string SectionName = "Settings";

public string QueueName { get; init; } = default!;
public string ConnectionString { get; init; } = default!;
public TimeSpan ConsumerDelay { get; init; } = TimeSpan.FromSeconds(1);
public TimeSpan ProducerDelay { get; init; } = TimeSpan.FromSeconds(1);
}
26 changes: 26 additions & 0 deletions src/Example05/Configuration/SettingsValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.Extensions.Options;

namespace Example05.Configuration;

public sealed class SettingsValidator : IValidateOptions<Settings>
{
public ValidateOptionsResult Validate(string? name, Settings? settings)
{
if (settings is null)
{
return ValidateOptionsResult.Fail($"{nameof(Settings)} is required.");
}

if (string.IsNullOrWhiteSpace(settings.QueueName))
{
return ValidateOptionsResult.Fail($"{nameof(Settings.QueueName)} is required.");
}

if (string.IsNullOrWhiteSpace(settings.ConnectionString))
{
return ValidateOptionsResult.Fail($"{nameof(Settings.ConnectionString)} is required.");
}

return ValidateOptionsResult.Success;
}
}
25 changes: 25 additions & 0 deletions src/Example05/Consumers/MessageConsumer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Example05.Configuration;
using Example05.Contracts;
using Example05.Extensions;
using Microsoft.Extensions.Options;

namespace Example05.Consumers;

public sealed class MessageConsumer
{
private readonly IOptions<Settings> _options;
private readonly ILogger<MessageConsumer> _logger;

public MessageConsumer(IOptions<Settings> options, ILogger<MessageConsumer> logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

public async Task Handle(Message message)
{
_logger.LogConsumedMessage(message.Id);

await Task.Delay(_options.Value.ConsumerDelay);
}
}
13 changes: 13 additions & 0 deletions src/Example05/Contracts/Message.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Example05.Contracts;

public sealed record Message
{
public Guid Id { get; init; }
public string Text { get; init; }

public Message()
{
Id = Guid.NewGuid();
Text = $"Text for Id {Id}";
}
}
47 changes: 47 additions & 0 deletions src/Example05/DependencyInjection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Example05.Configuration;
using Example05.Consumers;
using Example05.Contracts;
using Example05.Producers;
using Microsoft.Extensions.Options;
using Wolverine;
using Wolverine.AzureServiceBus;

namespace Example05;

public static class DependencyInjection
{
public static void AddServices(this HostApplicationBuilder builder)
{
builder.AddSettings();
builder.AddServiceBus();
}

private static void AddSettings(this HostApplicationBuilder builder)
{
builder.Services.Configure<Settings>(builder.Configuration.GetSection(Settings.SectionName));
builder.Services.AddSingleton<IValidateOptions<Settings>, SettingsValidator>();
}

private static void AddServiceBus(this HostApplicationBuilder builder)
{
var settings = builder.Configuration.GetSettings();

builder.UseWolverine(options =>
{
options.UseAzureServiceBus(settings.ConnectionString).AutoProvision();
options.PublishMessage<Message>().ToAzureServiceBusQueue(settings.QueueName);
options.ListenToAzureServiceBusQueue(settings.QueueName);
});

builder.Services.AddSingleton<MessageConsumer>();

builder.Services.AddHostedService<MessageProducer>();
}

private static Settings GetSettings(this ConfigurationManager configuration)
{
var settings = new Settings();
configuration.GetSection(Settings.SectionName).Bind(settings);
return settings;
}
}
13 changes: 13 additions & 0 deletions src/Example05/Example05.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">

<PropertyGroup>
<UserSecretsId>ServiceBusDemo-Example05-UserSecrets</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" />
<PackageReference Include="System.Text.Json" />
<PackageReference Include="WolverineFx.AzureServiceBus" />
</ItemGroup>

</Project>
10 changes: 10 additions & 0 deletions src/Example05/Extensions/LoggingExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Example05.Extensions;

public static partial class LoggingExtensions
{
[LoggerMessage(Level = LogLevel.Information, Message = "Message ({MessageId}) consumed.")]
public static partial void LogConsumedMessage(this ILogger logger, Guid messageId);

[LoggerMessage(Level = LogLevel.Information, Message = "Message ({MessageId}) produced.")]
public static partial void LogProducedMessage(this ILogger logger, Guid messageId);
}
35 changes: 35 additions & 0 deletions src/Example05/Producers/MessageProducer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Example05.Configuration;
using Example05.Contracts;
using Example05.Extensions;
using Microsoft.Extensions.Options;
using Wolverine;

namespace Example05.Producers;

public sealed class MessageProducer : BackgroundService
{
private readonly IServiceScopeFactory _factory;
private readonly IOptions<Settings> _options;
private readonly ILogger<MessageProducer> _logger;

public MessageProducer(IServiceScopeFactory factory, IOptions<Settings> options, ILogger<MessageProducer> logger)
{
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
using var scope = _factory.CreateScope();
var bus = scope.ServiceProvider.GetRequiredService<IMessageBus>();

while (!cancellationToken.IsCancellationRequested)
{
var message = new Message();
await bus.SendAsync(message);
_logger.LogProducedMessage(message.Id);
await Task.Delay(_options.Value.ProducerDelay, cancellationToken);
}
}
}
6 changes: 6 additions & 0 deletions src/Example05/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
using Example05;

var builder = Host.CreateApplicationBuilder(args);
builder.AddServices();
var host = builder.Build();
host.Run();
12 changes: 12 additions & 0 deletions src/Example05/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"Example05": {
"commandName": "Project",
"dotnetRunMessages": true,
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
8 changes: 8 additions & 0 deletions src/Example05/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Warning"
}
}
}
19 changes: 19 additions & 0 deletions src/Example05/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Warning"
},
"Console": {
"FormatterName": "simple",
"FormatterOptions": {
"SingleLine": true,
"TimestampFormat": "HH:mm:ss.ffff "
}
}
},
"Settings": {
"QueueName": "example05-queue",
"ConnectionString": "Endpoint=sb://namespace.service-bus.windows.net"
}
}

0 comments on commit cef81c2

Please sign in to comment.