所以在从接受的答案中查看this example 之后,我不太明白他要去哪里,所以我尝试了一些事情,我想我明白了他在说什么。因此,对于将来遇到此问题的人,我想将该示例更改为一个完整的示例。
所以我们要创建一个“共享方法”,如示例中所示:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace YouDontNeedToKnow.Core.Main.Hubs
{
internal class HubMethods<THub> where THub : Hub
{
private readonly IHubContext<THub> _hubContext;
public HubMethods(IHubContext<THub> hubContext)
{
_hubContext = hubContext;
}
public Task InvokeOnGroupAsync(string groupName, string method, params object[] args) =>
_hubContext.Clients.Group(groupName).InvokeAsync(method, args);
public Task InvokeOnAllAsync(string method, params object[] args) =>
_hubContext.Clients.All.InvokeAsync(method, args);
public Task AddConnectionIdToGroupAsync(string connectionId, string groupName) =>
_hubContext.Groups.AddAsync(connectionId, groupName);
// ...
}
}
然后,在您的 Hub 对象中,添加一个构造函数,如下所示:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace YouDontNeedToKnow.Core.Main.Hubs
{
internal class MyHub : Hub
{
public static string HubName => "myHub";
private readonly HubMethods<MyHub> _hubMethods;
public PlayerServicesHub(HubMethods<MyHub> hubMethods)
{
_hubMethods = hubMethods;
}
public override Task OnConnectedAsync()
{
return base.OnConnectedAsync();
}
}
}
在您的Startup.cs 中,您可以像这样注入共享类:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<HubMethods<MyHub>>();
services.AddSignalR();
services.AddMvc();
}
这仍然可以正常工作:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider sp)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseSignalR(routes =>
{
routes.MapHub<MyHub>(MyHub.HubName);
});
app.UseMvc();
// This is just an example line of how you can get the hub with context:
var myHub = sp.GetService<HubMethods<MyHub>>();
}