ASP.NET MVC中如何在SignalR Hub构造函数实现依赖注入?
解决ASP.NET MVC SignalR Hub构造函数依赖注入问题
首先明确:ASP.NET Core SignalR完全支持通过构造函数注入服务,不需要使用无参构造,你遇到连接失败的问题大概率是DI注册或SignalR配置有误,而非构造函数注入本身的问题。下面是具体解决步骤:
1. 修正服务注册
你当前Program.cs里的这行代码是错误的:
builder.Services.AddScoped<IServiceCollection, ServiceCollection>();
这不是注册INotificationService的正确方式,你需要把自己的服务注册到DI容器:
// 替换成你的NotificationService实现类 builder.Services.AddScoped<INotificationService, NotificationService>();
2. 确保SignalR服务已配置
在Program.cs中必须先添加SignalR服务,再映射Hub路由:
// 添加SignalR服务 builder.Services.AddSignalR(); var app = builder.Build(); // 其他中间件配置(比如静态文件、路由等)... // 映射你的Hub路由,路径要和前端连接时的路径对应 app.MapHub<ManualReconHub>("/manualReconHub");
3. 保留你的Hub构造函数注入代码
你的Hub代码完全没问题,不需要改成无参构造:
public class ManualReconHub : Hub<IManualReconHub> { private readonly INotificationService _notificationService; public static IList<string> AllDisabledRows = new List<string>(); public static IList<string> AllNotifications = new List<string>(); public ManualReconHub(INotificationService notificationService) { _notificationService = notificationService; } // 其他Hub方法... }
关于GlobalHost.DependencyResolver的说明
GlobalHost.DependencyResolver.Register是ASP.NET Framework(非Core)版本SignalR的用法,在ASP.NET Core里完全不需要用,直接用内置的DI系统即可,和你应用中其他服务的注入方式保持统一。
如果连接还是失败,可以检查:
- 前端连接Hub的路径是否和
MapHub配置的一致 INotificationService的实现类是否能被DI容器正确实例化(比如有没有循环依赖)
内容的提问来源于stack exchange,提问作者omo_codes
相关产品推荐
相关产品推荐

