-
Notifications
You must be signed in to change notification settings - Fork 2
messaging enrichers
Message enrichers are classes that can be registered during the bootstrap process and called before a message is published. These classes are used to add key/value pairs to the message before sending to registered message publishers.
Since messages are based on the IMessage interface, messages support a set of key/value pairs to which enrichers can add values without having to change the structure of the message.
The following example will add the computer name to each published message.
Add the following class to the Examples.Messaging.Info project.
using System;
using System.Threading.Tasks;
using NetFusion.Messaging.Enrichers;
using NetFusion.Messaging.Types.Attributes;
using NetFusion.Messaging.Types.Contracts;
namespace Examples.Messaging.Infra;
public class MachineNameEnricher : IMessageEnricher
{
public Task EnrichAsync(IMessage message)
{
message.Attributes.SetStringValue("MachineName", Environment.MachineName);
return Task.CompletedTask;
}
}
Enrichers need to be registered during the bootstrap process as follows:
.InitPluginConfig<MessageDispatchConfig>(c => c.AddEnricher<MachineNameEnricher>())
Examples.Messaging.WebApi/Program.cs
// ..
// Add Plugins to the Composite-Container:
builder.Services.CompositeContainer(builder.Configuration, new SerilogExtendedLogger())
.AddSettings()
.AddMessaging()
.InitPluginConfig<MessageDispatchConfig>(c => c.AddEnricher<MachineNameEnricher>())
.AddPlugin<InfraPlugin>()
.AddPlugin<AppPlugin>()
.AddPlugin<DomainPlugin>()
.AddPlugin<WebApiPlugin>()
.Compose();
// ..
A new domain-event and handler will be added to validate that machine name has been added to a published message.
Add the following domain-event:
Examples.Messaging.Domain/Events
using NetFusion.Messaging.Types;
namespace Demo.Domain.Events
{
public class NewCustomerDomainEvent : DomainEvent
{
public string FirstName { get; }
public string LastName { get; }
public NewCustomerDomainEvent(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
}
Add a corresponding message handler within the following directory: Examples.Messaging.App/Handlers
using System;
using Examples.Messaging.Domain.Events;
using NetFusion.Common.Extensions;
namespace Examples.Messaging.App.Handlers;
public class CustomerHandler
{
public void OnNewCustomer(NewCustomerDomainEvent domainEvent)
{
Console.WriteLine(domainEvent.ToIndentedJson());
}
}
Add a corresponding route to the InMemoryRouter class found here: Examples.Messaging.Infa/Routers
using Examples.Messaging.App.Handlers;
using Examples.Messaging.Domain.Events;
using NetFusion.Messaging.InProcess;
namespace Examples.Messaging.Infra.Routers;
public class InMemoryRouter : MessageRouter
{
protected override void OnConfigureRoutes()
{
OnDomainEvent<NewCustomerDomainEvent>(route =>
{
route.ToConsumer<CustomerHandler>(c => c.OnNewCustomer);
});
}
}
Define a model in the following location: Examples.Messaging.WebApi/Models
using System.ComponentModel.DataAnnotations;
namespace Examples.Messaging.WebApi.Models;
public class CustomerRegistration
{
[Required]
public string FirstName { get; set; } = string.Empty;
[Required]
public string LastName { get; set; } = string.Empty;
}
Define the below controller at the following location: Examples.Messaging.WebApi/Controllers
using Examples.Messaging.Domain.Events;
using Examples.Messaging.WebApi.Models;
using Microsoft.AspNetCore.Mvc;
using NetFusion.Messaging;
namespace Examples.Messaging.WebApi.Controllers;
[ApiController, Route("api/messaging")]
public class MessageController : ControllerBase
{
private readonly IMessagingService _messaging;
public MessageController(IMessagingService messaging)
{
_messaging = messaging;
}
[HttpPost("register/customer")]
public async Task<IActionResult> RegisterCustomer(CustomerRegistration model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var domainEvent = new NewCustomerDomainEvent(model.FirstName, model.LastName);
await _messaging.PublishAsync(domainEvent);
return Ok();
}
}
Test by running the microservice and posting a message to the following URL: http://localhost:5670/api/messaging/register/customer
cd ./src/Examples.Messaging.WebApi
dotnet run
When a message is published and logging is configured with the Debug log level, the messaging pipeline logs the complete message. The following log entry shows that the computer name has been added to the published message:
NetFusion comes with builtin enrichers that can be used. The following enrichers are available:
Enricher | Description |
---|---|
CorrelationEnricher | Adds a CorrelationId and MessageId to all published messages. A MessageId is unique for each message. The CorrelationId is unique for a given lifetime-scope. For example, if multiple messages are published in the same Http request, all messages will have the same CorrelationId but each message will have an unique MessageId values. Note: The enricher will only set the CorrelationId and MessageId if not already set on the message. |
DateOccurredEnricher | Adds an attribute named DateOccurred with the current date and time the message was published if not already present. |
HostEnricher | Adds an attribute named Microservice containing the name specified within the host's plugin definition. Also, an attribute named MicroserviceId is added with the unique identity value of the microservice specified within the host's plugin definition. |
These enrichers are contained within the following NuGet: NetFusion.Services.Messaging. Add all of the above by completing the following steps:
Install the NuGet package by running the following command:
dotnet add ./src/Components/Examples.Messaging.Infra package NetFusion.Services.Messaging
Then update the Program.cs file as follows:
// Add Plugins to the Composite-Container:
builder.Services.CompositeContainer(builder.Configuration, new SerilogExtendedLogger())
.AddSettings()
.AddMessaging()
.InitPluginConfig<MessageDispatchConfig>(c =>
{
c.AddEnricher<MachineNameEnricher>();
c.AddEnricher<CorrelationEnricher>();
c.AddEnricher<DateOccurredEnricher>();
c.AddEnricher<HostEnricher>();
})
.AddPlugin<InfraPlugin>()
.AddPlugin<AppPlugin>()
.AddPlugin<DomainPlugin>()
.AddPlugin<WebApiPlugin>()
.Compose();
Run the microservice again and post another message to the controller. Find the log entry of the published message and validate that the new message attributes have been added:
If the Bootstrap logs are expanded for the Messaging Plugin to display the MessageDispatchModule logs, a child collection lists all the configured Message Enrichers:
-
Templates
-
Resources
-
Bootstrapping
-
Modules Details
-
Settings
-
Validation
-
Monitoring
- Setup
- Commands
- Queries
- Domain Events
- Message Logs
- Message Publishers
- Message Enrichers
- Message Filters
-
Azure Service Bus
-
RabbitMQ
-
Redis
-
MongoDB