【问题标题】:How to activate IHubContext service in ASP.NET Core MVC?如何在 ASP.NET Core MVC 中激活 IHubContext 服务?
【发布时间】:2022-02-10 10:58:54
【问题描述】:

我在我的项目中使用了 signalR。有一个集线器,用户可以相互发送通知。在项目的登录部分,我想在用户登录时向管理员发送通知。我需要从控制器而不是客户端发送此通知。我试过了:

//after dependancy injection
_hubContext.Clients.User(***).SendAsync("LoginIn", "text1", "text2", "text3");

显示以下错误:

InvalidOperationException: 无法解析服务类型 'Microsoft.AspNetCore.SignalR.IHubContext' 尝试 激活“CustomizedIdentity.Controllers.HomeController”。

我尝试在 Services 中注册 IHubContext:

    builder.Services.AddScoped<IHubContext<MessageHub>>();

但它不起作用。

更新:

private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager;
private readonly IUserRepository _userRepository;
private readonly INotificationRepository _notificationRepository;
private readonly IHubContext _hubContext;
    
public HomeController(
    UserManager<AppUser> userManager,
    SignInManager<AppUser> signInManager,
    IUserRepository userRepository,
    INotificationRepository notificationRepository,
    IHubContext hubContext
)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _userRepository = userRepository;
    _notificationRepository = notificationRepository;
    _hubContext = hubContext;
}

【问题讨论】:

  • 向我们展示您的 HomeController 构造函数定义。
  • builder.Services.AddScoped&lt;IHubContext&lt;MessageHub&gt;&gt;(); IHubContext 的方式。你没有services.AddSignalR()吗?
  • services.AddSignalR() 存在。我已经有了。但是,显示错误。
  • IHubContext hubContext)更改为IHubContext&lt;MessageHub&gt; msgHubContext)

标签: asp.net-core signalr


【解决方案1】:

@Dai 解决了这个问题。我必须将IHubContext hubContext 更改为IHubContext&lt;MessageHub&gt; msgHubContext

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 2021-09-23
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多