ASP .NET Core-Startup类

默认项目新建Startup类,在程序入口函数构造IWebHost通过UserStartup<>指定的 ,主要包括ConfigureServices和Configure方法。应用程序启动时,调用StartuoLoader反射调用,完成服务注册和中间件注册,构建HTTP请求管道。

public class Startup
{
    // Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        ...
    }

    // Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
        ...
    }
}

1 ConfigureServices

配置服务讲服务注册到依赖注入容器中,在Configure前调用。通过调用IServiceCollection扩展方法进行注册,依赖容器可以被替换。

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>();
}

2 Configure

该方法接受IApplicationBuilder作为参数,同时可以接受一些可选参数,如IHostingEnvironment和ILoggerFactory。而且,在ConfigureServices方法中注册的其他服务,也可以直接在该方法中通过参数直接注入使用.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())//是否开发环境
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();//静态文件

//使用MVC 注册 包括路由
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
}

ASP.NET Core在调用之前已经默认注入了以下几个可用服务:

  • IConfiguration:用于读取应用程序配置。
  • IServiceCollection:可以理解为ASP.NET Core内置的依赖注入容器。
  • IApplicationBuilder:用于构建应用程序的请求管道。
  • IHostingEnvironment :提供了当前应用程序的运行的宿主环境配置信息。
    还可以使用已经注入的IServiceProvider、ILoggerFactory、ILogger、IApplicationLifetime等可用服务
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容