zoukankan      html  css  js  c++  java
  • 实现 Application_Start 和 Application_End

    理解 ASP.NET Core: 实现 Application_Start 和 Application_End

    在 ASP.NET 中两个常用的处理节点是 Application_Start() 和 Application_End(),它是在第一个请求到达网站的时候被执行和网站停止服务的时候被执行。通常用来进行网站的初始化处理和网站的扫尾处理。
    在 ASP.NET Core 中没有了默认的请求处理管道,也没有了 Global.asax,怎样处理这两个事件呢?

    在中间件中并不方便处理,中间件将在每个请求到达服务器的时候处理。
    这需要通过 ASP.NET Core 的应用程序生命周期来管理。

    在 ASP.NET Core 中,网站作为 Host 中寄宿的一个服务,服务使用一个生命周期管理对象 IApplicationLifetime 暴露其生命周期。该对象提供了 3 个重要的事件。我们可以在需要的事件上注册回调函数。

     /// <summary>
     /// Triggered when the application host has fully started and is about to wait
     /// for a graceful shutdown.
     /// </summary>
     CancellationToken ApplicationStarted { get; }
    
     /// <summary>
     /// Triggered when the application host is performing a graceful shutdown.
     /// Requests may still be in flight. Shutdown will block until this event completes.
     /// </summary>
     CancellationToken ApplicationStopping { get; }
    
     /// <summary>
     /// Triggered when the application host is performing a graceful shutdown.
        /// All requests should be complete at this point. Shutdown will block
        /// until this event completes.
        /// </summary>
        CancellationToken ApplicationStopped { get; }
    

    在 GitHub 中查看 IApplicationLifetime 源码

    IApplicationLifetime 同样可以通过注入而使用,例如,我们可以在 Configure() 方法中注入并使用该对象。

    public void Configure(IApplicationBuilder app, 
                          Microsoft.Extensions.Hosting.IHostApplicationLifetime applicationLifetime, 
                          ILoggerFactory loggerFactory)
    {
        // use applicationLifetime
    }
    

    使用注入的对象注册,这里注册了服务启动和停止事件。

    public class Startup 
    {
        private ILogger _logger;
    
        public void Configure(
          IApplicationBuilder app, 
          Microsoft.Extensions.Hosting.IHostApplicationLifetime applicationLifetime, 
          ILoggerFactory loggerFactory) 
        {
            applicationLifetime.ApplicationStarted.Register(OnStartup);
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
            ... 
            // add logger providers
            // loggerFactory.AddConsole()
            ...
            _logger = loggerFactory.CreateLogger("StartupLogger");
        }
    
        private void OnStartup()
        {
    
        }
    
        private void OnShutdown()
        {
             // use _logger here;
        }
    }
    

    见:https://stackoverflow.com/questions/41675577/where-can-i-log-an-asp-net-core-apps-start-stop-error-events

    需要注意的是,这里的事件没有使用 EventHandler,而是使用了 CancellationToken,原因是 CancellationToken 支持在多线程情况下使用。

  • 相关阅读:
    骗分
    【WC2016】鏖战表达式
    emacs配置
    UOJ NOI Round #4补题
    调整法
    IOC(控制反转)与DI(依赖注入)的个人理解。
    WPF进阶技巧和实战06-控件模板
    WPF进阶技巧和实战05-样式与行为
    WPF进阶技巧和实战04-资源
    WPF进阶技巧和实战03-控件(2-特殊容器)
  • 原文地址:https://www.cnblogs.com/haogj/p/13969359.html
Copyright © 2011-2022 走看看