gpt4 book ai didi

asp.net-core - SignalR hub 在 ASP.NET Core 中的 RabbitMQ 订阅处理程序中解析为 null

转载 作者:行者123 更新时间:2023-12-02 02:26:21 28 4
gpt4 key购买 nike

我有一个使用 RabbitMQ(通过 EasyNetQ)和 SignalR 的 ASP.NET Core MVC 项目。

接下来,我订阅了 RabbitMQ 消息,该消息应通过 SignalR 向客户端发送通知。

但遗憾的是,集线器始终解析为 null

一个有趣的观察是,当应用程序仍在启动并且队列中仍然有未确认的消息时,服务实际上可以很好地解析。

public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.RegisterEasyNetQ("host=localhost;virtualHost=/");
}

public void Configure(IApplicationBuilder app)
{
app.UseSignalR(route =>
{
route.MapHub<MyHub>("/mypath");
});

app.Use(async (context, next) =>
{
var bus = context.RequestServices.GetRequiredService<IBus>();

bus.SubscribeAsync<MyMessage>("MySubscription", async message =>
{
var hubContext = context.RequestServices
.GetRequiredService<IHubContext<MyHub>>();

// hubContext is null
await hubContext.Clients.All.SendAsync("MyNotification");
});

await next.Invoke();
});
}

我怀疑我在 app.Use 内注册订阅时可能做错了什么,但我似乎找不到任何有用的示例,所以这是我能想到的最好的例子.

我使用的是 ASP.NET Core 3 预览版 5,我不知道这是否与我的问题有关。

所以问题是:如何在消息订阅处理程序中获取集线器上下文?

更新

我检查了GetRequiredService docs如果服务无法解析,调用实际上应该抛出 InvalidOperationException,但事实并非如此。它返回 null,据我所知,这是不可能的(除非默认容器支持空值实例的注册)。

最佳答案

this issue 的帮助下我成功解决了这个问题通过实现 IHostedService 来代替。

public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.RegisterEasyNetQ("host=localhost;virtualHost=/");
services.AddHostedService<MyHostedService>();
}

public void Configure(IApplicationBuilder app)
{
app.UseSignalR(route =>
{
route.MapHub<MyHub>("/mypath");
});
}

public class MyHostedService : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;

public ServiceBusHostedService(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
}

protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
var scope = _serviceScopeFactory.CreateScope();
var bus = scope.ServiceProvider.GetRequiredService<IBus>();

bus.SubscribeAsync<MyMessage>("MySubscription", async message =>
{
var hubContext = scope.ServiceProvider.GetRequiredService<IHubContext<MyHub>>();

await hubContext.Clients
.All
.SendAsync("MyNotification", cancellationToken: stoppingToken);
});

return Task.CompletedTask;
}
}

关于asp.net-core - SignalR hub 在 ASP.NET Core 中的 RabbitMQ 订阅处理程序中解析为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56360983/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com