Page 36 - MSDN Magazine, September 2017
P. 36

happening to the console (which is great because it’s useful for debugging). On the other hand, if you set the environment to Production, you won’t get any console logging except for warnings and errors (which is also great because console logging is slow and should be kept to a minimum in production).
If you have experience with ASP.NET Core 1.0 and 1.1, you might notice that the ConfigureAppConfiguration method is new to 2.0. Previously, it was common to create an IConfiguration as part of the Startup type’s creation. Using the new ConfigureAppConfiguration method is a useful alternative because it updates the IConfiguration object stored in the application’s dependency injection (DI) con- tainer for easy future retrieval and makes configuration settings available even earlier in your application’s lifetime.
ASP.NET Core Logging
As with configuration setup, if you’re familiar with earlier versions ofASP.NETCoreyoumightrememberloggingsetupbeingdone in Startup.cs instead of in Program.cs. In ASP.NET Core 2.0, log- ging setup can now be done when building an IWebHost via the ConfigureLogging method.
It’s still possible to set up logging in Startup (using services.Add- Logging in Startup.ConfigureServices), but by configuring logging at Web host-creation time, the Startup type is streamlined and log- ging is available even earlier in the app startup process.
Alsolikeconfiguration,ASP.NETCoreloggingisextensible. Different providers are registered to log to different endpoints. Many providers are available immediately with a reference to Microsoft.AspNetCore.All, and even more are available from the .NET developer community.
As can be seen in WebHost.CreateDefaultBuilder’s source code, logging providers can be added by calling provider-specific exten- sion methods like AddDebug or AddConsole on ILoggingBuilder. If you use WebHost.CreateDefaultBuilder but still want to register logging providers other than the default Debug and Console ones, it’s possible to do so with an additional call to ConfigureLogging on the IWebHostBuilder returned by CreateDefaultBuilder.
Once logging has been configured and providers registered, ASP.NETCorewillautomaticallylogmessagesregardingitswork to process incoming requests. You can also log your own diag- nostic messages by requesting an ILogger object via dependency injection (more on this in the next section). Calls to ILogger.Log and level-specific variants (like LogCritical, LogInformation and so on) are used to log messages.
The Startup Type
Now that you’ve looked at Program.cs to see how the Web host is created, let’s jump over to Startup.cs. The Startup type that your app should use is indicated by the call to UseStartup when creating the IWebHost. Not a lot has changed in Startup.cs in ASP.NET Core 2.0 (except for it becoming simpler because logging and configuration are set up in Program.cs), but I’ll briefly review the Startup type’s two important methods because they’re so central to an ASP.NET Core app.
Dependency Injection The Startup type’s ConfigureServices method adds services to the application’s dependency injection
container. All ASP.NET Core apps have a default dependency injec- tion container to store services for later use. This allows services to be made available without tight coupling to the components that depend on them. You’ve already seen a couple examples of this—both ConfigureAppConfiguration and ConfigureLogging will add ser- vices to the container for use later in your application. At run time, if an instance of a type is called for, ASP.NET Core will automatically retrieve the object from the dependency injection container if possible.
For example, your ASP.NET Core 2.0 project’s Startup class has a constructor that takes an IConfiguration parameter. This con- structor will be called automatically when your IWebHost begins to run. When that happens, ASP.NET Core will supply the required IConfiguration argument from the dependency injection container.
As another example, if you want to log messages from a Razor Page, you can request a logger object as a parameter to the page model’s constructor (like how Startup requests an IConfiguration object) or in cshtml with the @inject syntax, as the following shows:
@using Microsoft.Extensions.Logging @inject ILogger<Index_Page> logger
@functions {
public void OnGet()
{
} }
Something similar could be done to retrieve an IConfiguration object or any other type that has been registered as a service. In this way, the Startup type, Razor Pages, controllers and so forth, can loosely depend on services provided in the dependency injection container.
As mentioned at the beginning of this section, services are added to the dependency injection container in the Startup.ConfigureServices method. The project template you used to create your application already has one call in ConfigureServices: services.AddMvc. As you might guess, this registers services needed by the MVC framework.
Another type of service that’s common to see registered in the ConfigureServices method is Entity Framework Core. Although it’s not used in this sample, apps that make use of Entity Framework Core typically register the DbContexts needed for working with Entity Framework models using calls to services.AddDbContext.
Youcanalsoregisteryourowntypesandservicesherebycalling services.AddTransient, services.AddScoped or services.Add- Singleton (depending on the lifetime required for dependency injection-provided objects). Registering as a singleton will result in a single instance of the service that’s returned every time its
Figure 3 ASP.NET Core Settings File
logger.LogInformation("Beginning GET");
{
"Logging": {
"IncludeScopes": false, "Debug": {
"LogLevel": { "Default": "Warning"
} },
"Console": { "LogLevel": {
"Default": "Warning" }
} }
}
32 msdn magazine
ASP.NET Core































































   34   35   36   37   38