.NET Core.net 技术分享asp.net

ASP.NET Core基本原理(1)-Application

2016-12-02  本文已影响213人  CharlieChu

ASP.NET Core基本原理(1)-Application Startup

Startup类可以配置处理应用程序的所有请求的请求管道。
原文链接:Application Startup

Startup类

所有的ASP.NET应用都至少有一个Startup类,当应用启动时,ASP.NET会在主程序集中搜索Startup类(在任何命名空间下)。

Startup类必须包含一个Configure方法和一个可选的ConfigureServices方法,这两个方法都会在应用启动的时候被调用。

Configure方法

Configure方法用于指定ASP.NET应用程序将如何响应HTTP请求。添加中间件(Middleware)到一个通过依赖注入所提供的IApplicationBuilder实例可以配置请求管道。

下面是默认网站的模板,多个扩展方法被用于配置管道以支持BrowserLink、错误页、静态文件、ASP.NET MVC以及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?}");
    });
}

每一个Use扩展方法添加一个中间件到请求管道。比如,UseMVC方法会添加路由中间件到请求管道,并将MVC配置成默认的处理器。

ConfigureServices方法

Startup类可以包含一个带有IServiceCollection参数和IServiceProvider返回值的ConfigureServices方法。ConfigureServices方法会在Configure方法之前被调用,因为一些功能必须在接入到请求管道之前被添加。

为了添加一些功能需要在IServiceCollection中通过Add[Something]扩展方法进行实质性的配置,下面的代码中配置应用去使用Entity Framework,Identity和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>();
}

通过依赖注入可以在你的应用中将服务添加到服务容器中。

服务会在应用启动时可用

ASP.NET Core依赖注入会在应用程序启动的时候提供应用服务。你可以在Startup类的构造函数中或者它的ConfigureConfigureServices方法中包含适当的接口作为参数请求那些服务。

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

个人博客

我的个人博客

上一篇下一篇

猜你喜欢

热点阅读