如何在 ASP.NET Core 6 中配置我的事件总线 - 迁移到 .NET 6

How can I configure my event bus in ASP.NET Core 6 - Migration to .NET 6

我想从 ASP.NET Core 5 迁移到 ASP.NET Core 6。如何在 .NET 6 中通过事件总线进行配置?

这是我在 ASP.NET Core 5 中的代码:

IEventBus.cs class

public interface IEventBus
{
    void Publish<TEvent>(TEvent @event)
        where TEvent : Event;

    void Subscribe<TEvent, TEventHandler>()
        where TEvent : Event
        where TEventHandler : IEventHandler<TEvent>;

    void Unsubscribe<TEvent, TEventHandler>()
        where TEvent : Event
        where TEventHandler : IEventHandler<TEvent>;
}

Startup.cs class

private void ConfigureEventBusHandlers(IApplicationBuilder app)
{
    var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
    eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();
}

该代码适用于 ASP.NET Core 5。但是在 .NET 6 中,我遇到了一个错误。

这是我在 ASP.NET Core 6 中的代码:

var app = builder.Build();

var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>();
eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();

这里是错误:

WebApplication does not contain a definition for 'ApplicationServices'

我也无法注入IApplicationBuilder

Program.cs 中试试这个代码:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEventBus,EventBus>();


ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();
var eventBus = serviceProvider.GetRequiredService<IEventBus>();
eventBus.Subscribe<MessageSentEvent, MessageSentEventHandler>();