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 的最佳实践案例,使得不同组件之间的通信更加灵活和解耦。