ASP .NET Core-Startup类

2018-10-24  本文已影响0人  无为无味无心

默认项目新建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在调用之前已经默认注入了以下几个可用服务:

上一篇 下一篇

猜你喜欢

热点阅读