Skip to content

Instantly share code, notes, and snippets.

@mattpieterse
Created September 25, 2024 08:08
Show Gist options
  • Save mattpieterse/e9af35c68a9d1770602e4c63ff5e1c41 to your computer and use it in GitHub Desktop.
Save mattpieterse/e9af35c68a9d1770602e4c63ff5e1c41 to your computer and use it in GitHub Desktop.
public sealed class QueueService
{
private readonly QueueClient _queueClient;
public QueueService(QueueServiceClient serviceClient, string container)
{
_queueClient = serviceClient.GetQueueClient(container.ToLower());
if (_queueClient.Exists() is false) {
_queueClient.CreateIfNotExists();
}
}
// - Controllers
public async Task SendToQueueAsync(string message)
{
await _queueClient.SendMessageAsync(message);
}
public async Task SendToQueueAsync(IEnumerable<string> messages)
{
var queue = new List<string>(messages);
foreach (var message in queue) {
await _queueClient.SendMessageAsync(message);
}
}
public async Task<IEnumerable<QueueMessage>> FetchAllAsync()
{
var queue = await _queueClient.ReceiveMessagesAsync(maxMessages: 32);
return new List<QueueMessage>(queue);
}
public async Task<IEnumerable<QueueMessage>> FetchAllAsync(int results)
{
var queue = await _queueClient.ReceiveMessagesAsync(maxMessages: results);
return new List<QueueMessage>(queue);
}
public async Task<QueueMessage> FetchOneAsync()
{
var message = await _queueClient.ReceiveMessageAsync();
return message;
}
public async Task<IEnumerable<PeekedMessage>> FetchAllIncognitoAsync()
{
var queue = await _queueClient.PeekMessagesAsync(maxMessages: 32);
return new List<PeekedMessage>(queue);
}
public async Task<IEnumerable<PeekedMessage>> FetchAllIncognitoAsync(int results)
{
var queue = await _queueClient.PeekMessagesAsync(maxMessages: results);
return new List<PeekedMessage>(queue);
}
public async Task<PeekedMessage> FetchOneIncognitoAsync()
{
var message = await _queueClient.PeekMessageAsync();
return message;
}
public async Task ClearAll()
{
await _queueClient.ClearMessagesAsync();
}
}
public sealed class QueueServiceFactory(QueueServiceClient serviceClient)
{
public QueueService Create(string container) => new(serviceClient, container);
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
var connect = builder.Configuration.GetConnectionString("AzureStorage");
builder.Services
.AddSingleton((x) => new QueueServiceClient(connect))
.AddScoped<QueueServiceFactory>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment