简体   繁体   中英

Startup.cs vs Program.cs in ASP.NET Core 2

I looked through the documentation on the Microsoft website and there are two places where we can set up the configuration.

We can do it either in Startup.cs or Program.cs. However, Program.cs has the same methods that are available in Startup.cs

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

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureServices(services =>
            {
                //same as ConfigureServices method in Startup.cs
                services.AddAutofac();
            })
            .Configure(app =>
            {
                //same as Configure method in Startup.cs
                app.UseMvc();
            })
            .Build();
}

Is the only purpose for the existence of "Startup.cs" to move some of the configuration out of "Program.cs"? Could we remove this file altogether and keep the entire configuration in "Program.cs"?

Could we remove this class altogether and keep entire configuration in Program.cs ?

Yes

Documentation explains

Convenience methods

To configure services and the request processing pipeline without using a Startup class, call ConfigureServices and Configure convenience methods on the host builder. Multiple calls to ConfigureServices append to one another. If multiple Configure method calls exist, the last Configure call is used.

It is more about the configuring of the builder than the actual Program.cs . That is just the default template class used to hold main entry to the application.

Reference App startup in ASP.NET Core

Program.cs is where the application starts.

Startup.cs is where lot of the configuration happens.

The idea for this separation is based on SOLID principles' first principle- SRP (Single Responsibility Principle). SOLID principles make software designs more understandable, flexible, and maintainable.

Single Responsibility Principle (SRP) states that a class or a method should only do one thing (or should have only one job). If you look at the Startup.cs, it does exactly this making it easy to read and understand the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM