ASP.NET Core中的托管设计现在有一个新的通用主机(.NET Core 2.1+),将来将取代Web主机。
使用Microsoft.Extensions.Hosting
接口的IHost
和IHostBuilder
有多种启动应用程序的方法。
我知道使用async
与sync
之间的区别,但所有这些选项之间有什么区别?使用Run
与Start
以及在IHostBuilder
上调用还是在IHost
上调用?
请参见下面代码中的选项// 1
、// 2
、// 3
和//4
:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MyNamespace
{
class Program
{
static async Task Main(string[] args)
{
IHostBuilder builder = CreateBuilder();
// 1 - Call Run on the builder (async)
await builder.RunConsoleAsync(); // extension method
// 2 - Call Start on the builder (sync)
builder.Start(); // extension method
IHost host = builder.Build(); // Call Build on the builder to get a host
// 3 - Call Run on the host (sync / async)
host.Run(); // extension method
await host.RunAsync(); // extension method
// 4 - Call Start on the host (sync / async)
host.Start(); // extension method
await host.StartAsync(); // class method
}
private static IHostBuilder CreateBuilder() => new HostBuilder()
.ConfigureAppConfiguration((hostingContext, config) =>
{
//...
})
.ConfigureLogging((hostingContext, logging) => {
//...
})
.ConfigureServices((hostContext, services) =>
{
//...
services.AddSingleton<IHostedService, MyService>();
});
}
}
RunConsoleAsync()
怎么样? - Pang