EventBus 是一種用于在應用程序組件之間進行解耦通信的設計模式。在 C# 中,可以使用第三方庫如 Prism、MediatR 或 NServiceBus 來實現 EventBus。以下是一個使用 MediatR 實現 EventBus 的最佳實踐案例:
public class UserRegisteredEvent : INotification
{
public string Username { get; set; }
}
public class UserRegisteredHandler : INotificationHandler<UserRegisteredEvent>
{
public Task Handle(UserRegisteredEvent notification, CancellationToken cancellationToken)
{
Console.WriteLine($"User {notification.Username} has been registered.");
return Task.CompletedTask;
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMediatR(typeof(Startup));
services.AddTransient<INotificationHandler<UserRegisteredEvent>, UserRegisteredHandler>();
}
public class UserService
{
private readonly IMediator _mediator;
public UserService(IMediator mediator)
{
_mediator = mediator;
}
public async Task RegisterUser(string username)
{
// Register user logic
await _mediator.Publish(new UserRegisteredEvent { Username = username });
}
}
public class UserController : Controller
{
private readonly UserService _userService;
public UserController(UserService userService)
{
_userService = userService;
}
[HttpPost]
public async Task<IActionResult> RegisterUser(string username)
{
await _userService.RegisterUser(username);
return Ok();
}
}
通過以上步驟,我們成功實現了 EventBus 的最佳實踐案例,使得不同組件之間的通信更加靈活和解耦。