呼叫另一个班级的 Hub

问题描述

我收到以下错误

system.invalidOperationException: '尝试激活'Rfid.RfidEngine' 时无法解析类型'Microsoft.AspNetCore.SignalR.IHubContext`1[Common.RfidHub]' 的服务。'

关于var rfidEngine = serviceProvider.GetService<IRfidEngine>();

我有这个代码

开始

public void ConfigureServices(IServiceCollection services)
{
    services.AddSignalR();
    var collection = new ServiceCollection();
    collection.AddScoped<IApplicationLogger,ApplicationLogger>();
    collection.AddScoped<IRfidEngine,RfidEngine>();
    
    IServiceProvider serviceProvider = collection.BuildServiceProvider();

    var applicationLogger = serviceProvider.GetService<IApplicationLogger>();
    applicationLogger.LoggingSettings = applicationSetting.LoggingSetting;

    var signalR = serviceProvider.GetService<IHubContext<RfidHub>>();

    var applicationLogger = serviceProvider.GetService<IApplicationLogger>();
    applicationLogger.LoggingSettings = applicationSetting.LoggingSetting;

    var rfidEngine = serviceProvider.GetService<IRfidEngine>();
    rfidEngine.Start();
    
    applicationLogger.Loginformation($@"Program has started",LoggerType.Console);
}

public void Configure(IApplicationBuilder app)
{
    app.UseCors("ApplicationCors");
    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapHub<RfidHub>("/rfidhub");
    });
}

中心

public class RfidHub : Hub
{
    public async Task SendReadings(string user,string message)
    {
        await Clients.All.SendAsync("ReceiveReading",user,message);
    }
}

RfidEngine

public class RfidEngine : Idisposable,IRfidEngine
{
    public RfidEngine(IApplicationLogger applicationLogger,IHubContext<RfidHub> hubContext)
    {
        this.applicationLogger = applicationLogger;
        this.hubContext = hubContext;
    }

    private void SendViaHub(string message)
    {
        hubContext.Clients.All.SendAsync("ReceiveReadings",message);
    }
}

这是我的 Signalr 版本:

<ItemGroup>
  <packagereference Include="Microsoft.AspNetCore.SignalR.Client" Version="5.0.8" />
  <packagereference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.2" />
  <packagereference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>

我需要能够在不同的类上调用 HubContext。我可以尝试什么来解决这个问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)