gpt4 book ai didi

c# - 如何将 SignalR hub 上下文传递到 ASP .NET Core 2.1 上的 Hangfire 作业?

转载 作者:行者123 更新时间:2023-12-03 00:55:47 26 4
gpt4 key购买 nike

如何将 SignalR hub 上下文传递到 ASP .NET Core 2.1 上的 Hangfire 作业?

由于向 Hangfire 传递参数是通过序列化/反序列化完成的,因此 Hangfire 似乎很难重建 SignalR hub 上下文。

我使用以下方式安排作业(在我的 Controller 中):

BackgroundJob.Schedule(() => _hubContext.Clients.All.SendAsync(
"MyMessage",
"MyMessageContent",
System.Threading.CancellationToken.None),
TimeSpan.FromMinutes(2));

然后 2 分钟后,当作业尝试执行时,出现错误:

Newtonsoft.Json.JsonSerializationException: Could not create an instance of type Microsoft.AspNetCore.SignalR.IClientProxy. Type is an interface or abstract class and cannot be instantiated.

有什么想法吗?

更新1

我最终使用了 Startup.cs 中定义的静态上下文,并从 Configure() 分配

hbctx = app.ApplicationServices.GetRequiredService<IHubContext<MySignalRHub>>(); 

所以现在 Hangfire 安排了一个使用静态上下文的集线器助手:

BackgroundJob.Schedule(() => new MyHubHelper().Send(), TimeSpan.FromMinutes(2)); 

集线器助手通过 Startup.hbctx

获取上下文

尽管这有效,但有点臭

更新2

我也尝试使用 Access SignalR Hub without Constructor Injection 中的方法:

我的后台作业调度变成:

BackgroundJob.Schedule(() => Startup.GetService().SendOutAlert(2), TimeSpan.FromMinutes(2));

但是这一次,当我到达上面一行时出现了异常:

An unhandled exception has occurred while executing the request System.ObjectDisposedException: Cannot access a disposed object. Object name: 'IServiceProvider'.

更新3

谢谢大家。解决方案是创建一个帮助程序,通过 DI 通过其构造函数获取 hubcontext,然后使用hangfire 将帮助程序方法 Send 安排为后台作业。

public interface IMyHubHelper
{
void SendOutAlert(String userId);
}

public class MyHubHelper : IMyHubHelper
{
private readonly IHubContext<MySignalRHub> _hubContext;

public MyHubHelper(IHubContext<MySignalRHub> hubContext)
{
_hubContext = hubContext;
}

public void SendOutAlert(String userId)
{
_hubContext.Clients.All.SendAsync("ReceiveMessage", userId, "msg");
}
}

然后从任何地方启动后台作业:

BackgroundJob.Schedule<MyHubHelper>( x => x.SendOutAlert(userId), TimeSpan.FromMinutes(2));

最佳答案

Nkosi 的回答建议使用 Schedule<T>泛型向我指出了我使用的最终解决方案:

首先,我的MySignalRHub只是一个继承自Hub的空类。

public class MySignalRHub 
{
}

然后,我创建了一个集线器助手,用于在 MySignalRHub 上维护集线器上下文。 hubcontext 通过 ASP.Net Core 内置 DI 机制注入(inject)到 helper 类中(如 here 所述)。

辅助类:

public class MyHubHelper : IMyHubHelper
{
private readonly IHubContext<MySignalRHub> _hubContext;

public MyHubHelper(IHubContext<MySignalRHub> hubContext)
{
_hubContext = hubContext;
}

public void SendData(String data)
{
_hubContext.Clients.All.SendAsync("ReceiveMessage", data);
}
}

辅助界面:

public interface IMyHubHelper
{
void SendData(String data);
}

最后,我可以使用 Hangfire 从代码中的任何位置安排方法 SendData()集线器助手作为后台作业:

BackgroundJob.Schedule<MyHubHelper>(h => h.SendData(myData), TimeSpan.FromMinutes(2));

关于c# - 如何将 SignalR hub 上下文传递到 ASP .NET Core 2.1 上的 Hangfire 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53538213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com