I can't seem to the following code working. All I'm doing is in ConfigureServies
calling _serviceProvider.GetService<IConnectionManager>();
and saving it in a static field and trying to use it later to get access to a IConnectionManager
and subsequently call GetHubContext<MyHub>
so I can broadcast messages to all connected clients.
_connectionManager.GetHubContext<MyHub>().Clients.All.doSomethingOnClients();
Just as a test, the same line of code inside a webapi controller action method works fine! (with IConnectionManager injected via constructor). That makes me believe my signalr set up is just fine, just how I got things in the startup class is wrong somewhere. GetHashCode
on the IConnectionManager
in startup and my controller gives different hash codes. I just need to hook things up on the ApplicationLifetime OnStartUp ...
Can you help me understand where things are going wrong please?
public class Startup
{
public static IServiceProvider _serviceProvider;
public static IConnectionManager _connectionManager;
private readonly IHostingEnvironment _hostingEnv;
public IConfigurationRoot Configuration { get; }
public Startup (IHostingEnvironment env)
{
// ...
}
public void ConfigureServices (IServiceCollection services)
{
// ....
services.AddSignalR(options => {
options.Hubs.EnableDetailedErrors = true;
});
services.AddMvc();
// ...
_serviceProvider = services.BuildServiceProvider();
_connectionManager = _serviceProvider.GetService<IConnectionManager>();
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
{
// ...
applicationLifetime.ApplicationStarted.Register(OnStartUp);
// ...
app.UseMvc(routes => {
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
app.UseSignalR();
// ...
}
public void OnStartUp ()
{
var x = _serviceProvider.GetService<MySingletonObject>();
// MySingletonObject has a VersionUpdated event handler
x.VersionUpdated += OnUpdate;
}
private void OnUpdate (object sender, EventArgs e)
{
// I get here everytime my singleton gets updated fine!
// but the following does not work
_connectionManager.GetHubContext<MyHub>().Clients.All.doSomethingOnClients();
}
}
I am using "Microsoft.AspNetCore.SignalR.Server/0.2.0-alpha1-22362".