.NET Core笔记-Host

IHost接口:

    public interface IHost : IDisposable
    {
        IServiceProvider Services {get;}

        Task StartAsync(CancellationToken cancellationToken = default(CancellationToken));

        Task StopAsync(CancellationToken cancellationToken = default(CancellationToken));
    }

Services属性,通过该属性可以拿到所有Host初始化时所注入的对象信息
IHostBuilder接口所承担的核心功能就是程序的初始化,通过:IHost Build()来完成,
IHostBuilder初始化内容包括以下功能:

HostConfiguration、HostingEnvironment、HostBuilderContext、ServiceCollection

以上功能的初始化是通过IHostBuilder提供的接口获取用户输入的信息后,通过调用Build()方法来完成初始化。以下为IHostBuilder接口代码:

    public interface IHostBuilder
    {
        IDictionary<object, object> Properties
        {
            get;
        }

        IHostBuilder ConfigureHostConfiguration(Action<IConfigurationBuilder> configureDelegate);//配置HostConfiguration

        IHostBuilder ConfigureAppConfiguration(Action<HostBuilderContext, IConfigurationBuilder> configureDelegate);

        IHostBuilder ConfigureServices(Action<HostBuilderContext, IServiceCollection> configureDelegate);//配置ServiceCollection

        IHostBuilder UseServiceProviderFactory<TContainerBuilder>(IServiceProviderFactory<TContainerBuilder> factory);

        IHostBuilder UseServiceProviderFactory<TContainerBuilder>(Func<HostBuilderContext, IServiceProviderFactory<TContainerBuilder>> factory);

        IHostBuilder ConfigureContainer<TContainerBuilder>(Action<HostBuilderContext, TContainerBuilder> configureDelegate);

        IHost Build();
    }

IHostApplicationLifetime接口:
Host生命周期订阅接口,该接口提供了一种我们可以在程序运行期间进行管理的功能,如程序的启动与停止事件的订阅。

public interface IHostApplicationLifetime
    {
        CancellationToken ApplicationStarted
        {
            get;
        }

        CancellationToken ApplicationStopping
        {
            get;
        }

        CancellationToken ApplicationStopped
        {
            get;
        }

        void StopApplication();
    }

订阅声明周期事件:

 applicationLifetime.ApplicationStarted.Register(() =>
            {
                app.ApplicationServices.GetService<ShopInfoexBus>().SyncSsoShop(); //同步SSO店铺信息
            });
上一篇:.NET 云原生架构师训练营(模块二 基础巩固 EF Core 更新和迁移)--学习笔记


下一篇:ASP.NET Core中处理中止的请求