ASP.NET Core 中的 startup类

发布时间:2020-09-01 15:34:17 作者:VOLVO之悦
来源:网络 阅读:1547

原文地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup


下文:

--Startup类

--Configure方法

--ConfigureServices方法

--可启用的服务(Services Available in Startup)

--其他资源


Startup类配置请求管道,处理所有应用程序接收的请求

The Startup class configures the request pipeline that handles all requests made to the application.


Startup

asp.net core需要启动类,通常以“Startup”命名,在程序WebHostBuilderExtensions中的UseStartup<TStartup>中指定Startup类名。

ASP.NET Core apps require a Startup class. By convention, the Startup class is named "Startup". You specify the startup class name in the Main programs WebHostBuilderExtensions UseStartup<TStartup> method.


你能分别定义Startup类在不同的环境(Environment),并在运行时选择适当的一个启动,如果在WebHost的配置或操作中指定了startupAssembly程序集,托管将加载startup程序集并查找Startup 或 Startup(Environment)类型,参考 StartupLoader  FindStartupType 和 Working with multiple environments,建议使用UseStartup<TStartup> .

You can define separate Startup classes for different environments, and the appropriate one will be selected at runtime. If you specify startupAssembly in the WebHost configuration or options, hosting will load that startup assembly and search for a Startup or Startup[Environment] type. See FindStartupType in StartupLoader and Working with multiple environmentsUseStartup<TStartup> is the recommended approach.



Startup类构造函数能接受通过依赖注入的依赖关系,你能用IHostingEnvironment设置配置,用ILoggerFactory设置logging提供程序。

The Startup class constructor can accept dependencies that are provided through dependency injection. You can use IHostingEnvironment to set up configuration sources and ILoggerFactory to set up logging providers.



Startup类必须包含 方法 而 方法可选,两个方法都在程序启动时调用,这个类也可包括这些方法的特定环境版本。

The Startup class must include a Configure method and can optionally include a ConfigureServices method, both of which are called when the application starts. The class can also include environment-specific versions of these methods.


了解关于在程序启动时的异常处理

Learn about handling exceptions during application startup.



Configure方法

configure方法用于指定ASP.NET程序如何响应HTTP请求,通过将中间件组件添加到由依赖注入提供的IApplicationBuilder实例中来配置请求管道。

The Configure method is used to specify how the ASP.NET application will respond to HTTP requests. The request pipeline is configured by adding middleware components to an IApplicationBuilder instance that is provided by dependency injection.


下面是来自默认网站模板的示例,对管道增加一些扩展方法用于支持  BrowserLink, error pages, static files, ASP.NET MVC, and Identity.

In the following example from the default web site template, several extension methods are used to configure the pipeline with support for BrowserLink, error pages, static files, ASP.NET MVC, and Identity



public void Configure(IApplicationBuilder app, IHostingEnvironment env,
                         ILoggerFactory loggerFactory)
{
 
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));    
    loggerFactory.AddDebug();    
    
    if (env.IsDevelopment())
    {    app.UseDeveloperExceptionPage();
         app.UseDatabaseErrorPage();
         app.UseBrowserLink();
    }
    else{        
        app.UseExceptionHandler("/Home/Error");
    }    
    
    app.UseStaticFiles();    
    app.UseIdentity();    
    
    app.UseMvc(routes =>{
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}


每个扩展方法添加一个中间件组件到请求管道中,例如,UseMvc扩展方法添加routing中间件到请求管道中并配置将MVC做为默认处理

Each Use extension method adds a middleware component to the request pipeline. For instance, the UseMvc extension method adds the routing middleware to the request pipeline and configures MVCas the default handler.


关于IApplicationBuilder的详细信息见 中间件。

For more information about how to use IApplicationBuilder, see Middleware.


也可以在方法签名中指定一些其他服务,如 IHostingEnvironment 和 ILoggerFactory,在这种情况下如果他们可用将被注入这些服务。

Additional services, like IHostingEnvironment and ILoggerFactory may also be specified in the method signature, in which case these services will be injected if they are available.


ConfigureServices方法

ConfigureServices方法是可选的,但若调用将在 Configure 之前被调用(一些功能会在链接到请求管道之前添加上),配置操作在方法中设置。

The ConfigureServices method is optional; but if used, it's called before the Configure method by the runtime (some features are added before they're wired up to the request pipeline). Configuration options are set in this method.


对于需要大量设置的功能,用  IServiceCollection的 Add[Service]扩展方法,下面是默认网站模板示例,将 Entity Framework, Identity, and MVC配置到程序中。

For features that require substantial setup there are Add[Service] extension methods on IServiceCollection. This example from the default web site template configures the app to use services for Entity Framework, Identity, and MVC.


public void ConfigureServices(IServiceCollection services)
{    
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
        
    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}


向服务容器中添加服务,使他们可以通过依赖注入在你的程序中使用。

Adding services to the services container makes them available within your application via dependency injection.


Startup可用的服务

ASP.NET Core 依赖注入 是在 程序的startup中 提供程序服务,你能请求这些服务通过 Startup类的构造函数 或 它的Configure和 ConfigureServices 发放中 将适当的接口作为一个参数传入。

ASP.NET Core dependency injection provides application services during an application's startup. You can request these services by including the appropriate interface as a parameter on your Startup class's constructor or one of its Configure or ConfigureServices methods.


按调用顺序看 Startup类中的每个方法,服务作为一个参数被请求

Looking at each method in the Startup class in the order in which they are called, the following services may be requested as parameters:


其他资源

  1. Working with Multiple Environments

  2. Middleware

  3. Logging

  4. Configuration


推荐阅读:
  1. 为什么你需要将代码迁移到ASP.NET Core 2.0?
  2. asp.net core如何配置

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

asp net core

上一篇:Mac Book中Java环境变量设置的方法

下一篇:调试Node.js程序的方法是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》