gpt4 book ai didi

asp.net-core - .NET 6 IHubContext 依赖注入(inject)

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

我正在开发一个简单的 .NET 6 应用程序,以在我们的前端应用程序中启用数据更新通知。我以前在 .NET 5 中构建过类似的东西,但我遇到了一个让我难过的 DI 问题。在 5 中,所有自动映射的集线器都有一个在容器中为它们设置的 IHubContext。在 6 中似乎不再是这种情况。

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]' while attempting to activate 'SignalRNotifications.Controllers.NotificationController'.

6 中新的非启动 DI 对我来说看起来很奇怪,但我只是没有看到任何可用的说明如何修复它。关于如何让 IHubContext 注入(inject)我的 Controller 有什么建议吗?

谢谢!

更新:这里是一些相关的代码:

using Microsoft.AspNetCore.Builder;
using SignalRNotifications.Hubs;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSignalR().AddAzureSignalR();


var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<NotificationHub>("/NotificationHub");
});

app.Run();

依赖注入(inject)以最可预测的方式在 Controller 中完成:

namespace SignalRNotifications.Controllers
{
[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
public class NotificationController : ControllerBase
{
private readonly IHubContext<NotificationHub> _notificationContext;

public NotificationController(IHubContext<NotificationHub> notificationContext)
{
_notificationContext = notificationContext;
}

最佳答案

System.InvalidOperationException: Unable to resolve service for type'Microsoft.AspNet.SignalR.IHubContext`1[SignalRNotifications.Hubs.NotificationHub]'while attempting to activate'SignalRNotifications.Controllers.NotificationController'.

此问题可能与您安装了错误版本的 SignalR 并添加了错误的命名空间引用有关。您正在使用 Microsoft.AspNet.SignalR.IHubContext,而不是 Microsoft.AspNetCore.SignalR.IHubContext

根据你的代码引用Asp.net Core SignalR document ,我创建了一个示例和 inject an instance of IHubContext in a controller ,一切正常。但我注意到,在使用 IHubContext 时,我们需要添加 using Microsoft.AspNetCore.SignalR; 命名空间,如下所示:

enter image description here

因此,请检查您的代码并尝试使用:

 using Microsoft.AspNetCore.SignalR;

关于asp.net-core - .NET 6 IHubContext 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71517673/

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