dev-fatih-erol / AspNetCore.EventBus.RabbitMQ

An EventBus base on Asp.net core 3.1 and RabbitMQ.
13 stars 2 forks source link
asp-net-core eventbus microservices rabbitmq

AspNetCore.EventBus.RabbitMQ

An EventBus base on Asp.net core 3.1 and RabbitMQ.

Made by inspiration from dotnet-architecture/eShopOnContainers, however there are some changes:

Add RabbitMQ EventBus

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddEventBusRabbitMQ(o =>
    {
       o.HostName = "localhost";
       o.UserName = "guest";
       o.Password = "guest";   
       o.QueueName = "event_bus_queue";
       o.BrokerName = "event_bus";
       o.RetryCount = 5;
    });
}

Add Custom EventBus

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddEventBus<CustomEventBus>();
}

!important: You must Add any LoggerProvider

Publish

public class UserRegisterEvent : Event
{
   public string Name { get; set; }
}

public class ValuesController : ControllerBase
{
  private readonly IEventBus _eventBus;

  public ValuesController(IEventBus eventBus)
  {
     _eventBus = eventBus;
  }

  [HttpPost]
  public ActionResult Post()
  {
     _eventBus.Publish(new UserRegisterEvent() { Name = "Fatih" });
     return Ok();
  }
}

Subscribe

public class UserRegisterEventHandler : IEventHandler<UserRegisterEvent>
{
   private readonly ILogger<UserRegisterEventHandler> _logger;

   public UserRegisterEventHandler(ILogger<UserRegisterEventHandler> logger)
   {
       _logger = logger;
   }

   public Task Handle(UserRegisterEvent @event)
   {
       _logger.LogInformation($"Welcome {@event.Name}!");
       return Task.FromResult(0);
   }
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<UserRegisterEventHandler>();
    ...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{        
    var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
    eventBus.Subscribe<UserRegisterEvent, UserRegisterEventHandler>();
    ...
}