Доступ к обобщенной коллекции хабов - PullRequest
0 голосов
/ 14 октября 2019

Меня мучает вопрос, если я добавлю несколько хабов (hub1, ​​hub2, ...) в проект (asp.core), могу ли я получить где-нибудь обобщенную коллекцию этих хабов или их контекстов? Что-то вроде:

public class SomeClass
{
    private readoly IHubCollection _collection;

    public SomeClass(IHubCollection collection)
        => _collection = collection;

    public void SomeMethod()
    {
        foreach(vat hub in _collection)
        {
           hub.SendSomeMessage();
        }
    }
}

1 Ответ

1 голос
/ 15 октября 2019

Для вашего требования есть некоторые ограничения, такие как концентратор должен реализовывать тот же интерфейс, который содержит SendSomeMessage.

Попробуйте выполнить следующие шаги:

  1. 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" };
        }       
}
...