【发布时间】: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<IHubContext<MessageHub>>();IHubContext 的方式。你没有services.AddSignalR()吗? -
services.AddSignalR()存在。我已经有了。但是,显示错误。 -
将
IHubContext hubContext)更改为IHubContext<MessageHub> msgHubContext)
标签: asp.net-core signalr