title
stringlengths
3
46
content
stringlengths
0
1.6k
11:309
11:310
This way of shutting down is triggered as soon as the cancellationToken enters a canceled state by another thread.
11:311
By default, the host has a 5-second timeout for shutting down; that is, it waits 5 seconds before exiting once a shutdown has been requested. This time can be changed within the ConfigureServices method, which is used to declare hosted services and other resources:
11:312
var myHost = Host.CreateDefaultBuilder(args)
11:313
.ConfigureServices(services =>
11:314
{
11:315
services.Configure<HostOptions>(option =>
11:316
{
11:317
option.ShutdownTimeout = System.TimeSpan.FromSeconds(10);
11:318
});
11:319
....
11:320
....
11:321
//further configuration
11:322
})
11:323
.Build();
11:324
11:325
However, increasing the host timeout doesn’t increase the orchestrator timeout, so if the host waits too long, the whole microservice is killed by the orchestrator.
11:326
If no cancellation token is explicitly passed to Run or RunAsync, a cancellation token is automatically generated and is automatically signaled when the operating system informs the application it is going to kill it. This cancellation token is passed to all hosted services to give them the opportunity to stop gracefully.
11:327
Hosted services are implementations of the IHostedService interface, whose only methods are StartAsync(cancellationToken) and StopAsync(cancellationToken).
11:328
Both methods are passed a cancellationToken. The cancellationToken in the StartAsync method signals that a shutdown was requested. The StartAsync method periodically checks this cancellationToken while performing all operations needed to start the host, and if it is signaled, the host start process is aborted. On the other hand, the cancellationToken in the StopAsync method signals that the shutdown timeout expired.
11:329
Hosted services can be declared in the same ConfigureServices method that’s used to define host options, as follows:
11:330
services.AddHostedService<MyHostedService>();
11:331
11:332
Most declarations inside ConfigureServices require the addition of the following namespace:
11:333
using Microsoft.Extensions.DependencyInjection;
11:334
11:335
Usually, the IHostedService interface isn’t implemented directly but can be inherited from the BackgroundService abstract class, which exposes the easier-to-implement ExecuteAsync(CancellationToken) method, which is where we can place the whole logic of the service. A shutdown is signaled by passing cancellationToken as an argument, which is easier to handle. We will look in more detail at an implementation of IHostedService in Chapter 14, Implementing Microservices with .NET.
11:336
To allow a hosted service to shut down the whole host, we need to declare an IApplicationLifetime interface as its constructor parameter:
11:337
public class MyHostedService: BackgroundService
11:338
{
11:339
private readonly IHostApplicationLifetime _applicationLifetime;
11:340
public MyHostedService(IHostApplicationLifetime applicationLifetime)
11:341
{
11:342
_applicationLifetime=applicationLifetime;
11:343
}
11:344
protected Task ExecuteAsync(CancellationToken token)
11:345
{
11:346
...
11:347
_applicationLifetime.StopApplication();
11:348
...
11:349
}
11:350
}
11:351
11:352
When the hosted service is created, it is automatically passed an implementation of IHostApplicationLifetime, whose StopApplication method will trigger the host shutdown. This implementation is handled automatically, but we can also declare custom resources whose instances will be automatically passed to all the host service constructors that declare them as parameters. Therefore, say we define a constructor like this one:
11:353
Public MyClass(MyResource x, IResourceInterface1 y)
11:354
{
11:355
...
11:356
}
11:357
11:358
There are several ways to define the resources needed by the preceding constructor:
11:359
services.AddTransient<MyResource>();
11:360
services.AddTransient<IResourceInterface1, MyResource1>();
11:361
services.AddSingleton<MyResource>();
11:362
services.AddSingleton<IResourceInterface1, MyResource1>();
11:363
11:364
When we use AddTransient, a different instance is created and passed to all the constructors that require an instance of that type. On the other hand, with AddSingleton, a unique instance is created and passed to all the constructors that require the declared type. The overload with two generic types allows you to pass an interface and a type that implements that interface. This way, a constructor requires the interface and is decoupled from the specific implementation of that interface.
11:365
If resource constructors contain parameters, they will be automatically instantiated with the types declared in ConfigureServices in a recursive fashion. This pattern of interaction, called dependency injection (DI), has already been discussed in detail in Chapter 6, Design Patterns and .NET 8 Implementation.
11:366
IHostBuilder also has a method we can use to define the default folder – that is, the folder used to resolve all relative paths mentioned in all .NET methods:
11:367
.UseContentRoot(`c:<deault path>`)
11:368
11:369
It also has methods that we can use to add logging targets:
11:370
.ConfigureLogging((hostContext, configLogging) =>
11:371
{
11:372
configLogging.AddConsole();
11:373
configLogging.AddDebug();
11:374
})
11:375
11:376
The previous example shows a console-based logging source, but we can also log in to Azure targets with adequate providers. The Further reading section contains links to some Azure logging providers that can work with microservices that have been deployed in Azure. Once you’ve configured logging, you can enable your hosted services and log custom messages by adding an ILogger<T> parameter in their constructors. ILogger<T> has methods for logging messages with several severity levels: Trace, Debug (lowest), Information, Warning, Error, Critical, and None (highest). In turn, the application configuration specifies the minimum severity level needed to actually output log messages. All messages that pass the severity filter are simultaneously sent to all configured targets.
11:377
The only purpose of the type T is to classify the message through its full name.
11:378
The developer can specify the minimum severity level in a configuration file. We may have different severity levels for each type of T.
11:379
For instance:
11:380
{
11:381
`Logging`: {
11:382
`LogLevel`: {
11:383
`Default`: `Information`,
11:384
`Microsoft.AspNetCore`: `Warning`
11:385
}
11:386
}
11:387
}
11:388
11:389
In the above configuration file, the default severity level is “Information”, but all types whose name starts with “Microsoft.AspNetCore” have a “Warning” severity level.
11:390
Finally, IHostBuilder has methods we can use to read configuration parameters from various sources:
11:391
.ConfigureAppConfiguration(configHost =>
11:392
{
11:393
configHost.AddJsonFile(`settings.json`, optional: true);
11:394
configHost.AddEnvironmentVariables(prefix: `PREFIX_`);
11:395
configHost.AddCommandLine(args);
11:396
})
11:397
11:398
The way parameters defined in configuration streams can be used from inside the application will be explained in more detail in Chapter 17, Presenting ASP.NET Core, which is dedicated to ASP.NET.
11:399
As we transition from the specificities of ASP.NET Core to the broader realm of application deployment and environment setup, an important tool comes into play – Visual Studio Docker support.
11:400
Visual Studio support for Docker
11:401
Visual Studio offers support for creating, debugging, and deploying Docker images. Docker deployment requires us to install Docker Desktop for Windows on our development machine so that we can run Docker images.
11:402
The download link can be found in the Technical requirements section at the beginning of this chapter. Before we start any development activity, we must ensure it is installed and running (you should see a Docker icon in the window notification bar when the Docker runtime is running).
11:403
Docker support will be described with a simple ASP.NET Core MVC project. Let’s create one. To do so, follow these steps:
11:404
11:405
Name the project MvcDockerTest.
11:406
For simplicity, disable authentication if it is not already disabled.
11:407
You are given the option to add Docker support when you create the project, but please don’t check the Docker support checkbox. You can test how Docker support can be added to any project after it has been created.
11:408
Once you have your ASP.NET MVC application scaffolded and running, right-click on its project icon in Solution Explorer, select Add, and then select Container Orchestrator Support | Docker Compose. If you installed both WSL and Windows Containers, a dialog for choosing between Linux and Windows will appear. Otherwise, Linux will be automatically chosen if you installed just WSL, and Windows if you installed just Windows Containers.