[Core 3.1] ASP.NET Core Startup 클래스 정리

728x90
반응형

Startup 클래스

- 앱에서 요구하는 Service 를 구성하는 ConfigureServices 메서드를 포함합니다.

- 앱의 요청 처리 파이프라인을 만드는 Configure 메서드가 포함됩니다. 

- ConfigureServicesConfigure 메서드는 앱 시작시 ASP.NET Core 런타임에 의해 호출됩니다.   

Service는 앱에서 사용되는 구성요소다. Ex) Logging 구성요소는 서비스다. 
이는 Startup.ConfigureServices 메서드에 추가된다.

 

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

앱의 호스트가 빌드 될 때 Startup 클래스가 지정되며, 호스트는 Startup 클래스 생성자에 사용할 수 있는 서비스를 제공합니다.  

 

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

앱은 ConfigureServices 를 통해 추가 서비스를 추가합니다.

그러면 호스트 및 앱 서비스 모두를 Configure 및 앱 전체에서 사용할 수 있다.

 


ConfigureServices Method

public void ConfigureServices(IServiceCollection services)
  1. 선택 사항이며,
  2. Configure 메서드 전에 호스트에 의해 호출되어 앱의 Services 를 구성한다.
  3. 여기서 구성 옵션이 규칙에 의해 설정 된다.

실질적인 설정이 필요한 기능의 경우 IServiceCollection Add{Service} 확장 메서드가 있습니다. 

예를 들어 

  • AddDbContext, 
  • AddDefaultIdentity, 
  • AddEntityFrameworkStores
  • AddRazorPages 
  • AddControllersWithViews 가 있습니다.

Configure Method

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

 

Configure 메서드는 앱이 HTTP 요청에 응답하는 방식을 지정하는 데 사용됩니다.

요청 파이프라인은 미들웨어 구성 요소를 IApplicationBuilder 인스턴스에 추가하여 구성됩니다.

IApplicationBuilder는 Configure 메서드에 사용할 수 있지만 서비스 컨테이너에 등록되지 않습니다.

호스팅이 IApplicationBuilder를 만들고 Configure에 직접 전달합니다.

 

ASP.NET Core 템플릿은 다음을 지원하는 파이프라인을 구성합니다.

  • 개발자 예외 페이지
  • 예외 처리기
  • HSTS(HTTP 엄격한 전송 보안)
  • HTTPS 리디렉션
  • 정적 파일
  • ASP.NET Core MVC 및 Razor Pages



728x90