冠军

导航

实现 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 支持在多线程情况下使用。

posted on 2020-11-26 09:33  冠军  阅读(1036)  评论(3编辑  收藏  举报