I am trying to build a simple ASP.NET 5 app with SignalR which should push messages to clients at regular intervals (e.g. implement a dashboard with values pushed from the server to the browser.)
I researched some posts such as http://arulselvan.net/realtime-dashboard-asp-net-signalr-angularjs-d3js/ or http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html. They recommend implementing a timer in a class implementing IRegisteredObject
from the System.Web.Hosting
namespace.
However, I don't seem to be able to locate the namespace where IRegisteredObject
lives in ASP.NET 5. System.Web
no longer exists in ASP.NET 5.
I haven't been able to find any info on it online.
What is the substitute for it in ASP.NET 5?
UPDATE
I am trying the following solution:
create a service encapsulating the timer
register it in Startup.cs
as a singleton service, e.g.
public class Ticker
{
Timer timer = new Timer(1000);
public Ticker()
{
timer.Elapsed += Timer_Elapsed;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
// do something
}
}
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// ...
Ticker ticker = new Ticker();
ServiceDescriptor sd = new ServiceDescriptor(typeof(Ticker), ticker);
services.Add(sd);
// ...
}
How about this approach?
IRegisteredObject
basically just gives a way of notifying the implementing class of impending doom, once your instance is registered with HostingEnvironment.RegisterObject
.
In .net core there is no need to implement any interface. The corresponding method of HostingEnvironment.RegisterObject
is IHostApplicationLifetime.ApplicationStopping
.Register
method.
In your application IoC, make sure to get a dependency on IHostApplicationLifetime
for an object or job manager or whatever to be able to register, or wire it up somehow in Startup.cs Configure
method, where an instance of this interface can be accessed by the framework IoC:
public void Configure(IApplicationBuilder app,
IHostApplicationLifetime applicationLifetime)
{
// Pipeline setup code ...
applicationLifetime.ApplicationStopping.Register(() => {
// notify long-running tasks of pending doom
});
}
Edit for asp.net core v2 and later: The interface IHostedService
and implementation BackgroundService
should also be mentioned here, as it's a relevant alternative for the same scenario.
Edit for asp.net core v3 and later: The interface IApplicationLifetime
is marked as obsolete (since ~3.0), use IHostApplicationLifetime
for new development.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With