Home > OS >  How can I configure by event bus in ASP.NET Core 6 - Migration to .NET 6
How can I configure by event bus in ASP.NET Core 6 - Migration to .NET 6

Time:02-13

I want to migrate from ASP.NET Core 5 to ASP.NET Core 6. How can I configure by event bus in .NET 6?

Here is my code in 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>();
}

The code works on ASP.NET Core 5. But in .NET 6, I encounter an error.

Here is my code in ASP.NET Core 6:

var app = builder.Build();

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

And here is the error:

WebApplication does not contain a definition for 'ApplicationServices'

I could not inject IApplicationBuilder either.

CodePudding user response:

In Program.cs try this code:

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


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