A series exploring ASP.NET Core 3.0: new project file, Program.cs and generic host

Introduction: In this article we look at some of the basic part of ASP.Net Core 3.0 applications - .csproj project file and the Program.cs file. I will introduce some of them in ASP.NET Core 2.x change from the default template, and discuss some of the changes to the API.

 

Explore ASP.Net Core 3.0 Series II: talk ASP.Net Core 3.0 of Startup.cs

Explore ASP.Net Core 3.0 series three: ASP.Net Core 3.0 The Service provider validation

Explore ASP.Net Core 3.0 Series 4: running asynchronous tasks when you start the application in ASP.NET Core 3.0

Explore ASP.Net Core 3.0 series five: introducing IHostLifetime and start interacting clarify Generic Host

Explore ASP.Net Core 3.0 Series Six: ASP.NET Core 3.0 new features start structured log information

I. INTRODUCTION

We know .Net Core 3.0 released on September 23, we have started in a production environment began to be used, let's look at some of the changes on the infrastructure:

(1) on Microsoft.AspNetCore.App NuGet no longer available.

(2) ASP.Net Core is now based generic host, rather than a Web Host.

If you want to upgrade to ASP.Net Core 2.x ASP.Net Core 3.0, please refer to the article: https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30? view = aspnetcore-3.0 & tabs = visual-studio

 

In this article we focus on ASP.Net Core newly created application in ..csproj and Program.cs file, a later article we will compare how Startup.cs come from 2.x and various changes changes in different templates (such as web webapi mvc, etc.).

Second, the new .csproj and shared framework changes

We create a new ASP.Net Core project, open the .csproj file, we will see the following changes:

 

If the project file in ASP.NET Core 2.x application of this comparison, then there are various similarities and differences:

(1) <TargetFramework> is netcoreapp3.0, rather than netcoreapp2.1 or 2.2, it is because we are creating a .Net Core project 3.0 instead of 2.1 / 2.2.

(2) <Project> element in the SDK is still Microsoft.Net.Sdk.Web.

(3) does not reference Microsoft.AspNetCore.App meta package.

(4) The last point is the most interesting change. In ASP.Net core2.1 / 2.2, you can refer to "sharing framework" yuan package, Microsoft.AspNetCore.App. Sharing framework provides many benefits, such as allowing you to avoid installing all applications manually in a single package and so on.

With .Net core 3.0, Microsoft is not shared framework as a Nuget package is published, it does not have Microsoft.AspNetCore.App version 3.0.0, sharing framework that is still installed along with the .NET Core as before, but refer to it in 3.0 different ways.

 

In ASP.NET Core 2.x, in order to share reference framework, your project file will add the following:

<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

In contrast, in 3.0, you can use <FrameworkReference> element to reference:

<ItemGroup>
  <FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

Careful students might say, why ASP.Net Core project file my newly created already exists Microsoft.AspNetCore.App, in fact, in .Net core of the SDK Microsoft.Net.Sdk.Web 3.0 already included in it.

 

 

 

Third, the package is no longer available as a shared frame assembly

A major change in 3.0 is that you can not install a single NuGet packages, which was originally part of a shared framework, for example, in ASP.NET Core 2.x, you can rely on a single package, such as Microsoft.AspNetCore.Authentication , Microsoft.AspNetCore.Identity, rather than relying on the overall framework portion screenshot follows:

 

 Specifically refer to the article: https://github.com/aspnet/AspNetCore/issues/3756

This is often most useful to the library, because the application always depends on a shared framework, however, in .NET Core 3.0, this is no longer possible. NuGet these packages are no longer available, on the contrary, if the need to refer to any of these libraries, you must add <FrameworkReference> element from the library to your project file. Another thing to note is that some packages (such as EF Core and social authentication providers) are no longer part of a shared framework. If you need to use these packages, you must manually install NuGet package in the project.

For a complete list of the application package, please refer  https://github.com/aspnet/AspNetCore/issues/3755

Screenshot part as follows:

 

 

Four, .Net Core 3.0 of Program.cs

We glance feel ASP.Net Core 3.0 in Program.cs with .NET Core 2.x versions are very similar, but in fact many types have been changed. This is because in .NET Core 3.0, ASP.NET Core has been rebuilt as in the Generic Host , on the run, rather than using a separate WebHost.

 

 

 

 From the above chart, the existence of significant differences, generic host introduced in 2.1, this is a good idea, but a lot of problems, it creates more work for the library, but fortunately in 3.0 of this change should We can solve these problems.

In most cases, the end-use habits with you is very similar to the .NET Core 2.x, but it is divided into two logical steps, rather than a single method WebHost.CreateDefaultBuilder application configuration all content (), which has two a single method call:

(1) Host.CreateDefaultBuilder (): function is arranged app configuration items, logs, and dependency injection container.

(2) IHostBuilder.ConfigureWebHostDefaults (): role is to add all the required ASP.Net core applications, such as: the Kestrel configuration, using Startup.cs  to configure DI container and the intermediate pipe.

 

五、generic host builder

As I already mentioned, a generic host forms the basis for building ASP.NET Core 3.0 applications. It provides the basic elements used in Microsoft.Extensions ASP.NET Core * applications, such as: Logging, configuration and dependency injection.

The following code is a simplified version Host.CreateDefaultBuilder () method. It is similar to WebHost.CreateDefaultBuilder () method, but there are some interesting changes, I will discuss later.

public static IHostBuilder CreateDefaultBuilder(string[] args)
{
    var builder = new HostBuilder();

    builder.UseContentRoot(Directory.GetCurrentDirectory());
    builder.ConfigureHostConfiguration(config =>
    {
        // Uses DOTNET_ environment variables and command line args
    });

    builder.ConfigureAppConfiguration((hostingContext, config) =>
    {
        // JSON files, User secrets, environment variables and command line arguments
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        // Adds loggers for console, debug, event source, and EventLog (Windows only)
    })
    .UseDefaultServiceProvider((context, options) =>
    {
        // Configures DI provider validation
    });

    return builder;
}

 

In short, and there are about different compared to 2.x:

  • Use DOTNET_ prefix hosting environment variable configuration.
  • Using the command line variables host configuration.
  • Add an event source records and event logger provider.
  • Optional Enables verification ServiceProvider
  • No specific configurations WebHosting.

(1) The first point of interest is the arrangement of the host configuration, the environment variable for the Web host is configured to use default ASPNETCORE_, therefore, sets the environment setting ASPNETCORE_ENVIRONMENT configuration values. For generic host prefix is ​​now DOTNET_, and run any command passed to the application line arguments. Host configuration control application running in a hosting environment, content, and (usually together with IOptions Interface) and application configuration are separated.

(2) The main method is to configure your application, ConfigureAppConfiguration () has not changed, it still uses appsettings.json file, and a appsettings.ENV.json file, user secrets, environment variables, and command-line parameters.

Logging section (3) universal host has started in 3.0, it is still filtering through the application configuration log level configuration, and add the console and debug logger provider. However, it also adds EventSource  logging Provider, which is used for OS logging systems (such as LTTng on ETW and Linux on Windows) interface. In addition, only on Windows, recorder adds  Event the Log Provider ,, in order to write to the Windows event log.

 

Finally, generic host configuration dependency injection container in order to verify the scope when running in the development environment, as is done in the 2.x. Its purpose is to capture dependencies example, the range of service which the service is injected into Singleton. In 3.0, a generic host also enable ValidateOnBuild, this is the function I described in a subsequent post.

A generic host key point is that it is universal, that is to say, it does not have any specific relationship with ASP.NET Core or HTTP workloads. You can use as the basis for creating generic host console application or long-term service and typical ASP.NET Core applications. To illustrate this point, in 3.0, you have an additional method --ConfigureWebHostDefaults ().

 

Sixth, the use ConfigureWebHostDefaults restore function ASP.NETCore

This article is a long time, so I would not be here talking about a lot of details, but the ConfigureWebHostDefaults  extension methods for generic functions on the host to add "layers" ASP.NETCore. At the simplest level, this involves adding Kestrel Web server to the host, but there are other changes. The following is an overview of the method provides (including functional GenericWebHostBuilder provided):

  • ASPNETCORE_ prefix environment variable added to the host configuration (except prefix DOTNET_ variables and command-line parameters).
  • 添加GenericWebHostService,这是一个实现了IHostService接口的类,实际上运行在ASP.NET Core server,这是使ASP.NET Core可以重用通用主机的主要功能。
  • 添加了一个附加的应用程序配置源,StaticWebAssetsLoader,用于处理Razor UI类库中的静态文件(css / js)。
  • 使用默认值(与2.x相同)配置Kestrel
  • 添加HostFilteringStartupFilter(与2.x相同)
  • 如果ForwardedHeaders_Enabled配置值为true,即ASPNETCORE_FORWARDEDHEADERS_ENABLED环境变量为true,则添加ForwardedHeadersStartupFilter。
  • 在Windows上启用IIS集成。
  • 将端点路由服务(endpoint routing)添加到DI容器。

 

(1)其中的大部分与ASP.NET Core 2.x中的相同,不同之处在于:用于将应用程序作为IHostedService运行的基础结构; 端点路由,此路由在3.0中全局启用(而不是仅在2.2中针对MVC / Razor Pages启用); 和ForwardedHeadersStartupFilter。

(2)ForwardedHeadersMiddleware从1.0开始就存在,在将应用程序托管在代理之后时必不可少,以确保您的应用程序能够处理SSL卸载并正确生成URL。 所更改的是,您只需设置环境变量即可将中间件配置为使用X-Forwarded-For和X-Forwarded-Proto标头。

 

七、总结

在本文中,我仅用两个文件深入研究了从ASP.NET Core 2.x到3.0的更改:.csproj项目文件和`Program.cs文件。 从表面上看,对这些文件的更改很小,因此从2.x移植到3.0并不难。 这种简单性掩盖了幕后的重大变化:共享框架发生了重大变化,并且ASP.NET Core已在通用主机之上重建。

我希望人们会遇到的最大问题是NuGet包之间的差异-一些应用程序将不得不删除对ASP.NET Core包的引用,同时添加对其他包的显式引用。 尽管不难解决,但对于不熟悉此更改的用户可能会造成混淆,因此应该首先怀疑任何问题。

 

 

翻译:Andrew Lock    https://andrewlock.net/exploring-the-new-project-file-program-and-the-generic-host-in-asp-net-core-3/

 

作者:郭峥

出处:http://www.cnblogs.com/runningsmallguo/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

Guess you like

Origin www.cnblogs.com/runningsmallguo/p/11616202.html