1.使用Microsoft.Extensions.Hosting插件,运行console项目
- 主要代码
#region 使用Microsoft.Extensions.Hosting插件,运行console项目
{
Console.WriteLine("Hello, World!");
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
IHost host = hostBuilder.Build();
host.Run();
}
#endregion
2.使用Microsoft.Extensions.Hosting插件,运行web项目
- 主要代码
#region 使用Microsoft.Extensions.Hosting插件,运行web项目
{
Console.WriteLine("Hello, World!");
WebApplicationBuilder hostBuilder = WebApplication.CreateBuilder(args);
IHost host = hostBuilder.Build();
host.Run();
}
#endregion
3.使用Microsoft.Extensions.Hosting插件,依赖注入组件使用
- 创建Person类
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public void Study() {
Console.WriteLine("Study");
}
- 主要代码
#region 使用Microsoft.Extensions.Hosting插件,依赖注入组件使用
{
Console.WriteLine("Hello, World!");
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
hostBuilder.Services.AddSingleton<Person>();
IHost host = hostBuilder.Build();
var person = host.Services.GetRequiredService<Person>();
person.Study();
host.Run();
}
#endregion
4.使用Microsoft.Extensions.Hosting插件,日志组件使用
- 创建Person类
public class Person
{
private readonly ILogger<Person> logger;
public Person(ILogger<Person> logger)
{
this.logger = logger;
}
public Guid Id { get; set; }
public string Name { get; set; }
public void Study() {
logger.LogError("Study");
Console.WriteLine("Study");
}
}
- 主要代码
#region 使用Microsoft.Extensions.Hosting插件,日志组件使用
{
Console.WriteLine("Hello, World!");
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
hostBuilder.Services.AddSingleton<Person>();
hostBuilder.Logging.AddConsole();
hostBuilder.Logging.AddFile(options =>
{
options.Files = new[] { new LogFileOptions { Path = "Logs/log.txt", MaxFileSize = 10 * 1024 * 1024 } };
});
IHost host = hostBuilder.Build();
var person = host.Services.GetRequiredService<Person>();
person.Study();
host.Run();
}
#endregion
5.使用Microsoft.Extensions.Hosting插件,配置组件使用
- 创建Person类
public class Person
{
private readonly ILogger<Person> logger;
private readonly IConfiguration configuration;
public Person(ILogger<Person> logger,IConfiguration configuration)
{
this.logger = logger;
this.configuration = configuration;
}
public Guid Id { get; set; }
public string Name { get; set; }
public void Study() {
var noImplicitAny = configuration["compilerOptions:noImplicitAny"];
Console.WriteLine("noImplicitAny:"+noImplicitAny);
logger.LogError("Study");
Console.WriteLine("Study");
}
}
- 主要代码
#region 使用Microsoft.Extensions.Hosting插件,配置组件使用
{
Console.WriteLine("Hello, World!");
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
hostBuilder.Services.AddSingleton<Person>();
hostBuilder.Logging.AddConsole();
hostBuilder.Logging.AddFile(options =>
{
options.Files = new[] { new LogFileOptions { Path = "Logs/log.txt", MaxFileSize = 10 * 1024 * 1024 } };
});
hostBuilder.Configuration.AddJsonFile("appsettings.json");
IHost host = hostBuilder.Build();
var person = host.Services.GetRequiredService<Person>();
person.Study();
host.Run();
}
#endregion
5.使用Microsoft.Extensions.Hosting插件,后台任务使用
- 第一种IHostedService
public class MyBackgroundService : IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("后台任务开始");
Task.Run(() => {
while (!cancellationToken.IsCancellationRequested) {
Console.WriteLine($"{DateTime.Now}");
Thread.Sleep(1000);
}
});
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("后台任务停止......");
return Task.CompletedTask;
}
}
- 第二种BackgroundService
public class BackgroundTask : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("后台线程2开始:");
await Task.Run(() =>
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine($"后台线程2开始:{DateTime.Now}");
Thread.Sleep(1000);
}
});
}
public override Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("后台线程2结束");
return Task.CompletedTask;
}
}
- 主要代码
#region 使用Microsoft.Extensions.Hosting插件,后台任务使用
{
Console.WriteLine("Hello, World!");
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
hostBuilder.Services.AddSingleton<Person>();
hostBuilder.Services.AddHostedService<MyBackgroundService>();
hostBuilder.Services.AddHostedService<BackgroundTask>();
hostBuilder.Logging.AddConsole();
hostBuilder.Logging.AddFile(options =>
{
options.Files = new[] { new LogFileOptions { Path = "Logs/log.txt", MaxFileSize = 10 * 1024 * 1024 } };
});
hostBuilder.Configuration.AddJsonFile("appsettings.json");
IHost host = hostBuilder.Build();
var person = host.Services.GetRequiredService<Person>();
person.Study();
host.Run();
}
#endregion
6.使用Microsoft.Extensions.Hosting插件,生命周期
- 主要代码
Console.WriteLine("Hello, World!");
HostApplicationBuilder hostBuilder = Host.CreateApplicationBuilder(args);
hostBuilder.Services.AddSingleton<Person>();
hostBuilder.Services.AddHostedService<MyBackgroundService>();
hostBuilder.Services.AddHostedService<BackgroundTask>();
hostBuilder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});
hostBuilder.Logging.AddConsole();
hostBuilder.Logging.AddFile(options =>
{
options.Files = new[] { new LogFileOptions { Path = "Logs/log.txt", MaxFileSize = 10 * 1024 * 1024 } };
});
hostBuilder.Configuration.AddJsonFile("appsettings.json");
IHost host = hostBuilder.Build();
IHostApplicationLifetime lifetime = host.Services.GetService<IHostApplicationLifetime>();
lifetime.ApplicationStarted.Register((o) =>
{
ServiceProvider serviceProvider = (ServiceProvider)o;
IDistributedCache distributedCache = serviceProvider.GetService<IDistributedCache>();
distributedCache.SetString("ceshi", "数据");
}, host.Services);
lifetime.ApplicationStopping.Register(() =>
{
Console.WriteLine($"应用程序正在停止");
});
lifetime.ApplicationStopped.Register((o) =>
{
ServiceProvider serviceProvider = (ServiceProvider)o;
IDistributedCache distributedCache = serviceProvider.GetService<IDistributedCache>();
distributedCache.Remove("ceshi");
}, host.Services);
var person = host.Services.GetRequiredService<Person>();
person.Study();
host.Run();
}
#endregion