微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

呼叫另一个班级的 Hub

如何解决呼叫另一个班级的 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 举报,一经查实,本站将立刻删除。