创建 .NET Core Console App

Visual Studio 2019 中创建一个 Console App

在解决方案中添加其他层, 创建类似于下图的解决方案项目结构:

添加 NuGet 包

在 控制台项目中添加以下三个NuGet包:

  1. Microsoft.Extensions.DependencyInjection;
  2. Microsoft.Extensions.Hosting;
  3. Microsoft.Extensions.Logging;

添加 DI 容器

打包 控制台项目中的 program.cs 文件,将其代码中的 main() 修改为以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{

var builder = new HostBuilder()
.ConfigureServices((hostContext, services)=> {
services.AddLogging(configure => configure.AddConsole());
services.AddTransient<MyApplication>();
services.AddSingleton<ISampleClient, SampleClient>();
services.AddTransient<HttpClient>();

});
var host = builder.Build();
using (var serviceScope = host.Services.CreateScope()) {
var services = serviceScope.ServiceProvider;
try
{
var myService = services.GetRequiredService<MyApplication>();
await myService.Run();
}
catch (Exception ex)
{
Console.WriteLine("Error Occured: {0}", ex);
}
}
}
}

控制台项目中的 MyApplication.cs 文件类似于以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MyApplication
{
private readonly ILogger _logger;
private readonly IBusinessLayer _business;
public MyApplication(ILogger<MyApplication> logger, IBusinessLayer business)
{
_logger = logger;
_business = business;
}

internal async Task Run()
{
_logger.LogInformation("Application {applicationEvent} at {dateTime}", "Started", DateTime.UtcNow);

_business.PerformBusiness();

_logger.LogInformation("Application {applicationEvent} at {dateTime}", "Ended", DateTime.UtcNow);

Console.WriteLine("PRESS <ENTER> TO EXIT");
Console.ReadKey();
}
}

===END===