An Event Bus Based on RabbitMQ, whose core code is from eShopOnContainers, I just pulled it out and made some extensions, fixes and improvements.
I currently only use it for microservices. If your project has only one ASP. NET Core project, then it may not be suitable for you.
PM> Install-Package Toosame.EventBus.RabbitMQ -Version 2.0.1
- Add Event
- Add Event Handler
- Publish Event in Controller
Create YourEvent.cs
public record class YourEvent : IntegrationEvent
{
public string Name { get; set; }
public int Age { get; set; }
}
Create YourEventHandler.cs
public class YourEventHandler : IIntegrationEventHandler<YourEvent>
{
private readonly IConfiguration _configuration;
public YourEventHandler(IConfiguration configuration){
//I'm just telling you that you can also use Dependency Injection Services.
_configuration = configuration;
}
public Task Handle(YourEvent @event)
{
//you can get @event.Name
//you can get @event.Age
//Do something...
return Task.CompletedTask;
}
}
public class HomeController : ControllerBase
{
private readonly IEventBus _eventBus;
public YourEventHandler(IEventBus eventBus){
_eventBus = eventBus;
}
[HttpGet]
public IAcionResult Index(){
_eventBus.Publish(new YourEvent(){
Name: "my name",
Age: 22
})
}
}
You can subscribe to the event you just created here.
- Configure appsettings.json
- Setup on
Program.cs
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"RabbitMQ": {
"EventBusConnection": "<yourRabbitMqHost>[:port(default 5672)]",
"EventBusUserName": "<rabbitMqUserName>",
"EventBusPassword": "<rabbitMqPassword>",
"EventBusRetryCount": 5,
"EventBusBrokeName": "<rabbitMqExchangeName>",
"SubscriptionClientName": "<queueName>" //It's better to have different microservices with different names
}
}
builder.Services.AddEventBus(Configuration.GetSection("RabbitMQ").Get<RabbitMQOption>(),
eventHandlers =>
{
eventHandlers.AddEventHandler<YourEventHandler1>();
eventHandlers.AddEventHandler<YourEventHandler2>();
});
app.UseEventBus(eventBus =>
{
eventBus.Subscribe<YourEvent1, YourEventHandler1>();
eventBus.Subscribe<YourEvent2, YourEventHandler2>();
});