Для вашего требования есть некоторые ограничения, такие как концентратор должен реализовывать тот же интерфейс, который содержит SendSomeMessage
.
Попробуйте выполнить следующие шаги:
IHub
public interface IHub
{
void SendSomeMessage();
}
ChatHub
public class ChatHub : Hub, IHub
{
public void Send(string name, string message)
{
// Call the broadcastMessage method to update clients.
Clients.All.SendAsync("broadcastMessage", name, message);
}
public void SendSomeMessage()
{
Clients.All.SendAsync("broadcastMessage", "hub", "hello");
}
}
Регистрация
Hub
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
services.AddMvc();
services.AddSingleton<ChatHub>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseFileServer();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chat");
});
app.UseMvcWithDefaultRoute();
}
}
UseCase
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly IServiceProvider _serviceProvider;
public ValuesController(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
// GET: api/<controller>
[HttpGet]
public async Task<IEnumerable<string>> Get()
{
var typesFromAssemblies = Assembly.GetExecutingAssembly().GetTypes().Where(x => x.BaseType == typeof(Hub));
foreach (var type in typesFromAssemblies)
{
var hub = _serviceProvider.GetService(type) as IHub;
hub.SendSomeMessage();
}
return new string[] { "value1", "value2" };
}
}