首页 > Web开发 > 详细

Asp.Net Core 应用程序启动(翻译)

时间:2018-01-14 16:20:45      阅读:258      评论:0      收藏:0      [点我收藏+]

Startup 用于配置服务和应用的请求管道。

The Startup class

Asp.Net Core 应用使用StartUp类。StartUp类:

1、可选地包含ConfigureServices 方法,配置应用的服务。

2、必须包含一个Configure 方法,创建应用的请求处理管道。

 

ConfigureServices 和 Configure 方法在应用启动时由运行时调用。

 1 public class Startup
 2 {
 3     // Use this method to add services to the container.
 4     public void ConfigureServices(IServiceCollection services)
 5     {
 6         ...
 7     }
 8 
 9     // Use this method to configure the HTTP request pipeline.
10     public void Configure(IApplicationBuilder app)
11     {
12         ...
13     }
14 }

 

用 WebHostBuilderExtensions UseStartup<TStartup> 方法明确  Startup ,如下:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

 

StartUp类构造函数接受 host 定义的依赖项。一个常见的使用依赖注入启动类是注入ihostingenvironment通过环境配置服务:

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        HostingEnvironment = env;
    }

    public IHostingEnvironment HostingEnvironment { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        if (HostingEnvironment.IsDevelopment())
        {
            // Development configuration
        }
        else
        {
            // Staging/Production configuration
        }
    }
}

一个可代替的方式注入IHostingStartup是使用约定的方式。应用为不同的环境定义独立的Startup类(比如:StartupDevelopment),运行时会选择适当的启动类。名称后缀与当前环境匹配的类是优先的。如果应用运行在开发环境,同时包含Startup 类和 StartupDevelopment 类,StartupDevelopment 类将会被使用。

 

The ConfigureServices method

 

ConfigureServices  方法:

1、可选

2、在 Configure 方法之前由Web host调用来配置应用程序的服务

3、配置选项按约定设置

 

 

 

 

翻译于官方文档。未完待续,有错误欢迎指正。

 

Asp.Net Core 应用程序启动(翻译)

原文:https://www.cnblogs.com/hzz521/p/8283500.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!