- ASP.NET Core uses a startup class, which is named
Startup
by convention.
- It optionally includes a
ConfigureServices
method to configure the app's services.
- It must include a
Configure
method to create the app's request processing pipeline.
- The
ConfigureServices
and Configure
are called by the runtime when the app starts.
- Specify the Startup class with the
WebHostBuilderExtensions UseStartup<TStartup>()
method:
public class Program
{
public static void Main(string[] args)
{
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
- The
Startup
class constructor accepts dependencies defined by the host.
- A common use of dependency injection into the
Startup
class is to inject:
IHostingEnvironment
to configure services by environment.
IConfiguration
to configure the app during startup.
public Startup(IHostingEnvironment env, IConfiguration config)
{
HostingEnvironment = env;
Configuration = config;
}
- An alternative to injecting
IHostingEnvironment
is to use a conventions-based approach.
- The app can define separate Startup classes for different environments (for example, StartupDevelopment).
- The class whose name suffix matches the current environment is prioritized.
The ConfigureServices
Method
- This method is called by the web host to configure the app's services. The web host provides some services that are available to the Startup class constructor.
- The app adds additional services via
ConfigureServices
.
- Both the host and app services are then available in Configure and throughout the application.
- The services are resolved via dependency injection or from
IApplicationBuilder.ApplicationServices
.
- The web host may configure some services before
Startup
methods are called.
- For features that require substantial setup, there are
Add[Service]
extension methods on IServiceCollection
.