首页 > 解决方案 > SignalR 可能无法在 .NET 5 中工作?无法解析类型“Microsoft.AspNetCore.SignalR.IHubContext`1[iBet.Server.Hubs.ChatHub]”的服务

问题描述

我正在尝试在 .NET 5 和 Angular 10 应用程序中设置聊天,但到目前为止,后端部分让我陷入了困境。每当我尝试访问 ChatController 时,我都会得到

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.SignalR.IHubContext`1[iBet.Server.Hubs.ChatHub]' while attempting to activate 'iBet.Server.Controllers.ChatController'.

这是控制器本身:

    [Produces("application/json")]
public class ChatController : ApiController
{
    private readonly IHubContext<ChatHub> _hubContext;

    public ChatController(IHubContext<ChatHub> hubContext)
    {
        _hubContext = hubContext;
    }

    [Route("send")]                                           
    [HttpPost]
    public IActionResult SendRequest([FromBody] MessageRequest message)
    {
        _hubContext.Clients.All.SendAsync("ReceiveOne", message.User, message.MessageText);
        return Ok(message.MessageText);
    }
}

这是我的启动:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSignalR();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseCors(options => options
           .AllowAnyOrigin()
           .AllowAnyHeader()
           .AllowAnyMethod());

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapHub<ChatHub>("/chatsocket");    
        });

    }

据我了解,一旦您放置 services.AddSignalR(); 它负责 DI,但在 .NET 5 中似乎有所不同,任何建议将不胜感激。

标签: c#.netasp.net-coresignalr

解决方案


推荐阅读