Service collection RabbitMQ extension
- Author
- Scott Rickman
- Last updated
- 2026-08-17
RabbitMq.cs
namespace RealWebDevelopers;
public class RabbitMq
{
public required string Host { get; set; }
}
Extensions.cs
namespace RealWebDevelopers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
public static class Extensions
{
public static void AddRabbitMq(this ServiceCollection services)
{
services.AddSingleton<IConnection>(implementationFactory =>
{
return new ConnectionFactory
{
HostName = implementationFactory.GetRequiredService<IOptions<RabbitMq>>().Value.Host,
}.CreateConnectionAsync().Result;
});
}
}
appsettings.json
{
"Logging": {
...
},
"RabbitMq": {
"Host": "localhost"
}
}
Program.cs
namespace RealWebDevelopers;
using Microsoft.Extensions.Options;
public class Program
{
public static void Main(string[] args)
{
// boiler plate web application
builder.Services.AddOptions<RabbitMq>().Bind(builder.Configuration.GetSection("RabbitMq"));
builder.Services.AddRabbitMq();
// etc.
}
}