ASP.NET 5中IRegisteredObject的替代方案是什么?

11

我正在尝试构建一个简单的ASP.NET 5应用程序,其中包含SignalR,它应该定期向客户端推送消息(例如,实现一个仪表板,将值从服务器推送到浏览器)。

我研究了一些帖子,例如http://arulselvan.net/realtime-dashboard-asp-net-signalr-angularjs-d3js/http://henriquat.re/server-integration/signalr/integrateWithSignalRHubs.html。它们建议在实现System.Web.Hosting命名空间中实现IRegisteredObject的类中实现一个计时器。

然而,我似乎无法找到ASP.NET 5中的IRegisteredObject所在的命名空间。在ASP.NET 5中,不存在System.Web命名空间。我没有在网上找到任何相关信息。在ASP.NET 5中,它的替代品是什么?

更新

我正在尝试以下解决方案:

  • 创建一个封装计时器的服务

  • Startup.cs中将其注册为单例服务,例如:

    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
        }
    }
    
    public void ConfigureServices(IServiceCollection services)
        {
            // ... 
            Ticker ticker = new Ticker();
            ServiceDescriptor sd = new ServiceDescriptor(typeof(Ticker), ticker);
            services.Add(sd);
            // ...
        }
    

    这种方法如何?


HostingEnvironment.QueueBackgroundWorkItem 方法怎么样?它是在 .NET 4.5 中引入的,取代了 IRegisteredObject - Anders
没有找到那个。它在 System.Web.Hosting 中 - 看起来这个命名空间已经不存在了,就像 System.Web 本身一样。 - AunAun
关于你的更新,有取消的概念,当应用程序池回收时,后台作业需要完成。 - Anders
1个回答

8

IRegisteredObject基本上只是提供了一种通知实现类即将过期的方法,一旦你的实例被HostingEnvironment.RegisterObject注册。

在 .net core 中不需要实现任何接口。相应的HostingEnvironment.RegisterObject方法对应的是IHostApplicationLifetime.ApplicationStopping方法。Register方法。

在您的应用程序 IoC 中,请务必获取 IHostApplicationLifetime 的依赖项以注册对象或作业管理器等,或者在Startup.csConfigure方法中进行某种方式的连接,该接口的实例可以由框架 IoC 访问:

public void Configure(IApplicationBuilder app,
    IHostApplicationLifetime applicationLifetime)
{
    // Pipeline setup code ...

    applicationLifetime.ApplicationStopping.Register(() => { 
        // notify long-running tasks of pending doom  
    });
}

针对 asp.net core v2 及更高版本进行编辑:在这里还应该提到接口IHostedService和实现BackgroundService,因为它是相同场景的相关替代方案。

针对 asp.net core v3 及更高版本进行编辑:接口IApplicationLifetime已被标记为过时(自 ~3.0 起),新开发请使用IHostApplicationLifetime


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接