QsMessaging is a .NET 8 library designed for sending and receiving messages between services or components of your application using RabbitMQ. It supports horizontal scalability, allowing multiple instances of the same service to handle messages efficiently.
Available on NuGet for seamless integration:
A simple, scalable messaging solution for distributed systems.
Install the package using the following command:
dotnet add package QsMessaging
Registering the library is simple. Add the following two lines of code to your Program.cs
:
// Add QsMessaging (use the default configuration)...
builder.Services.AddQsMessaging(options => { });
...
await host.UseQsMessaging();
RabbitMQ
- Host:
localhost
- UserName:
guest
- Password:
guest
- Port:
5672
Define a message contract:
public class RegularMessageContract
{
public required string MyTextMessage { get; set; }
}
Inject IQsMessaging
into your class:
public YourClass(IQsMessaging qsMessaging) {}
Then, use it to send a message:
await qsMessaging.SendMessageAsync(new RegularMessageContract { MyTextMessage = "My message." });
To handle the message, create a handler:
public class RegularMessageContractHandler : IQsMessageHandler<RegularMessageContract>
{
public Task<bool> Consumer(RegularMessageContract contractModel)
{
// Process the message here
return Task.FromResult(true);
}
}
You can also use the Request/Response pattern to send a request and await a response. This is useful when you need to communicate between services and expect a response.
Define the request and response contracts:
public class MyRequestContract
{
public required string RequestMessage { get; set; }
}
public class MyResponseContract
{
public required string ResponseMessage { get; set; }
}
To send a request and await a response, use the RequestResponse<TRequest, TResponse>
:
public class MyService
{
private readonly IQsMessaging _qsMessaging;
public MyService(IQsMessaging qsMessaging)
{
_qsMessaging = qsMessaging;
}
public async Task<MyResponseContract> SendRequestAsync(MyRequestContract request)
{
var response = await _qsMessaging.SendRequestResponseAsync<MyRequestContract, MyResponseContract>(request);
return response;
}
}
To handle requests, implement the IQsRequestResponseHandler<TRequest, TResponse>
interface:
public class MyRequestHandler : IQsRequestResponseHandler<MyRequestContract, MyResponseContract>
{
public Task<MyResponseContract> Handle(MyRequestContract request)
{
// Process the request and create a response
return Task.FromResult(new MyResponseContract { ResponseMessage = "Response to: " + request.RequestMessage });
}
}
That's all, folks!
For detailed documentation, visit the QsMessaging Wiki.