一、介绍

  官方文档中说,Microsoft.AspNetCore.App 元包(ASP.NET Core 2.1 或更高版本)包含通用主机的Microsoft.Extensions.Hosting包,当创建控制台项目以后并没有相应的包。

  在官方案例中所用的Nuget包有:

    1. Microsoft.Extensions.Hosting

    2. Microsoft.Extensions.Configuration.Json

    3. Microsoft.Extensions.Configuration.EnvironmentVariables

    4. Microsoft.Extensions.Configuration.CommandLine

    5. Microsoft.Extensions.DependencyInjection

    6. Microsoft.Extensions.Logging.Console

    7. Microsoft.Extensions.Logging.Debug

  托管服务实现 IHostedService 接口并且是执行代码的入口点。 每个 IHostedService 实现都按照 ConfigureServices 中服务注册的顺序执行。 主机启动时,每个 IHostedService 上都会调用 StartAsync。主机正常关闭时,以反向注册顺序调用 StopAsync。

  托管服务还有,BackgroundService:排队的后台任务,IScopedProcessingService:有作用域的服务

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO; namespace Haos.Develop.HostBuilders.Samples
{
class Program
{
static void Main(string[] args)
{
//Microsoft.Extensions.Hosting
var host = new HostBuilder()
.ConfigureHostConfiguration(builder => {
//Microsoft.Extensions.Configuration.Json
builder.AddJsonFile("hostsettings.json", true);
builder.AddJsonFile("appsettings.json", true);
})
.ConfigureAppConfiguration((context, builder) => {
var temp = context.Configuration["AllowedHosts"];
context.HostingEnvironment.ApplicationName = "this_is_text_host";
builder.SetBasePath(Directory.GetCurrentDirectory());
//Microsoft.Extensions.Configuration.EnvironmentVariables
builder.AddEnvironmentVariables("PREFIX_HAOS_");
//Microsoft.Extensions.Configuration.CommandLine
builder.AddCommandLine(args);
})
.ConfigureServices((context, services) => {
services.AddHostedService<MyHostedService>();
})
.ConfigureLogging((logging) => {
//Microsoft.Extensions.Logging.Console
logging.AddConsole();
//Microsoft.Extensions.Logging.Debug
logging.AddDebug();
})
.UseConsoleLifetime()
.Build(); host.Run();
}
}
}

二、主机配置

  默认的情况下,是不配置主机环境变量。需要配置可以调用ConfigureHostConfiguration和ConfigureAppConfiguration方法进行配置,并且他们可以同时调用多次得到累计结果

var host = new HostBuilder()
.ConfigureHostConfiguration(builder => {
  builder.AddJsonFile("hostsettings.json", true);
})
.ConfigureHostConfiguration(builder => {
builder.AddJsonFile("appsettings.json", true);
})
.ConfigureAppConfiguration((context, builder) => {//应用入口点的程序集的名称
context.HostingEnvironment.ApplicationName = "this_is_text_host";
//确定主机从哪里开始搜索内容文件
builder.SetBasePath(Directory.GetCurrentDirectory());
//设置应用的环境
builder.AddEnvironmentVariables("PREFIX_HAOS_");
})

  代码中调用两次ConfigureHostConfiguration方法都是加载配置文件。加载的文件在当前方法无法获取到文件的类容。例如第一次调用加载hostsettings.json文件无法立刻获取改文件内容。在加载appsettings.json这个方法里就能拿到hostsettings.json的内容

三、依赖关系注入,配置日志

  ConfigureServices:将服务添加到应用的依赖关系注入容器。 可多次调用 ConfigureServices,并得到累计结果。

  ConfigureLogging:添加一个委托,用于配置提供的 ILoggingBuilder。 可以利用相加结果多次调用 ConfigureLogging

 var host = new HostBuilder()
.ConfigureServices((context, services) => {
//Microsoft.Extensions.DependencyInjection
services.AddHostedService<MyHostedService>();
})
.ConfigureLogging((logging) => {
//Microsoft.Extensions.Logging.Console
logging.AddConsole();
//Microsoft.Extensions.Logging.Debug
logging.AddDebug();
})

 四、IApplicationLifetime接口和IHostedService接口的实现类

  IApplicationLifetime 允许启动后和关闭活动,包括正常关闭请求。通过构造函数将 IApplicationLifetime 服务注入到任何类中,用于注册事件

  ApplicationStarted:完全启动触发,ApplicationStopped:正在完成关闭触发,ApplicationStopping:正在执行关闭触发

  StopApplication() 方法用于关闭整个主机

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace Haos.Develop.HostBuilders.Samples
{
public class MyHostedService : IHostedService
{
/// <summary>
/// 日志
/// </summary>
private readonly ILogger _looger;
/// <summary>
/// 配置
/// </summary>
private readonly IConfiguration _configuration;
private readonly IApplicationLifetime _applicationLifetime; public MyHostedService(ILogger<MyHostedService> logger,IConfiguration configuration,IApplicationLifetime applicationLifetime)
{
_looger = logger;
_configuration = configuration;
_applicationLifetime = applicationLifetime;
} public Task StartAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
var stringStr = _configuration["Test_Code"];
//主机已完全启动
_applicationLifetime.ApplicationStarted.Register(() => _looger.LogInformation("status is started"));
//主机正在完成正常关闭,应处理所有请求
_applicationLifetime.ApplicationStopped.Register(()=> _looger.LogInformation(stringStr));
//主机正在执行正常关闭,仍在处理请求
_applicationLifetime.ApplicationStopping.Register(() => _looger.LogInformation("status is Stopping"));
int i = ;
Timer timer = new Timer(a => {
if (i == ) Close();
i++;
_looger.LogWarning("测试输出!");
}, null, , );
});
} public Task StopAsync(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
_looger.LogInformation("Application Shutdown");
Console.Read();
});
} /// <summary>
/// 请求应用终止.(整个应用)
/// </summary>
public void Close()
{
_applicationLifetime.StopApplication();
}
}
}

.Net Core 通用主机(Core 在控制台应用程序中的应用)的更多相关文章

  1. (16)ASP.NET Core 通用主机(HostBuilder)

    1.前言 ASP.NET Core应用程序可以配置和启动主机(Host).主机负责应用程序启动和生命周期管理.通用主机用于无法处理HTTP请求的应用程序.通用主机的用途是将HTTP管道从Web主机AP ...

  2. Net Core通用主机项目报错 程序不包含适合于入口点的静态Main

    Net Core通用主机的介绍: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/generic-host?view=as ...

  3. 在.NET Core控制台应用程序中使用强类型配置

    想象一下,你写一个控制台应用程序,你想要从配置文件中以强类型方式读取配置. .NET Core 可以帮助我们解决. 通常我会在ASP.NET Core MVC中演示,但简单起见,只在控制台应用程序中演 ...

  4. 控制台应用程序中添加对MFC的支持

    在windows控制台应用程序中,肯能会想使用一些MFC中的类,如CStringArray等,通过下面两步简单的设置可以添加对MFC的支持: 1.右击工程名 -> References 选择 A ...

  5. 在Windows控制台应用程序中使用CString

    CString是在windows平台下开发中经常使用的字符串类, CString已从MFC中剥离出来了,可以单独使用,只需引用atlstr.h头文件即可. include "stdafx.h ...

  6. 控制台应用程序中Main函数的args参数

    在VS中添加参数 菜单   项目   --   你的项目属性   --   调试   --   启动选项   --   命令行参数 参数之间用空格分隔开就可以了,如果参数有空格,以双引号风格

  7. C# 控制台应用程序中输出彩色字体

    using System; class Example { public static void Main() { // Get a string array with the names of Co ...

  8. hangfire控制台应用程序中添加控制面板

    1.使用nuget 管理包安装 Microsoft.AspNet.WebApi.OwinSelfHost 2.根目录添加新建类 名为:Startup.cs public class Startup { ...

  9. Asp.net Core 2.1新功能Generic Host(通用主机),了解一下

    什么是Generic Host ? 这是在Asp.Net Core 2.1加入了一种新的Host,现在2.1版本的Asp.Net Core中,有了两种可用的Host. Web Host –适用于托管W ...

随机推荐

  1. 通过 vuex 实现 vue-echarts 图表的手动 resize

    背景:项目有用到 vue-echarts, 百度推出的 vue 版本的 Echarts,图表自带响应式属性 auto-resize, 来实现窗口尺寸变化时,图表的尺寸自适应,但是发现它是靠监听 win ...

  2. C# 多进程安全

    多个应用程序同时写入数据到一个文件中时可用 public void WriteData(string dataWh, string filePath) { EventWaitHandle waitHa ...

  3. 零元学Expression Blend 4 - Chapter 24 以实作了解Cover Flow功能

    原文:零元学Expression Blend 4 - Chapter 24 以实作了解Cover Flow功能 今天要介绍一个Silverlight Toolkit内好用且在图片展示操作上很常见的元件 ...

  4. Android零基础入门第49节:AdapterViewFlipper图片轮播

    原文:Android零基础入门第49节:AdapterViewFlipper图片轮播 上一期学习了ExpandableListView的使用,你已经掌握了吗?本期开始学习AdapterViewFilp ...

  5. PHP trait 特性在 Laravel 中的使用个人心得

    trait 是在PHP5.4中为了方便代码复用的一种实现方式,但目前我在看的的PHP项目中较少看的有程序员去主动使用这个实现方式,在laravel中有很多 trait 的使用,关于trait 在 la ...

  6. 更换Qt QtEmbedded库的版本出现问题及解决(交叉编译OpenSSL)

    近日将QtEmbedded库的版本由4.7.0更新到4.7.4.工具链并未改变,仍为 Target: arm-none-linux-gnueabiConfigured with: ......Thre ...

  7. Understand the Qt containers(有对应表)

    Container classes are one of the cornerstones of object-oriented programming, invaluable tools that ...

  8. 理解call(),apply(),bind()

    三者皆是修改this指向call(this指向,参数,参数,参数...) ====>深研究:https://developer.mozilla.org/zh-CN/docs/Web/JavaSc ...

  9. ZooKeeper 系列(二)—— Zookeeper单机环境和集群环境搭建

    一.单机环境搭建         1.1 下载         1.2 解压         1.3 配置环境变量         1.4 修改配置         1.5 启动         1. ...

  10. 浅谈IHttpHandler

    在Web应用开发或接口开发时,处理请求接口IHttpHandler随处可见,那么我们这次来简单聊一下这个接口. ASP.NET响应Http请求时常用的两个处理接口,分别是IHttpHandler和IH ...