Why doesn't ASP.NET Core force the Startup type to implement an interface

Viewed 238

The ASP.NET Core configuration relies on a Startup class that should have one Configure method and that can optionally include a ConfigureServices method.

I was wondering why not force this class to implement an interface containing those two methods to get all the benefits of strong typing.

I know that the true reason lies unreachable in the mind of the designers of the framework, but can anybody give a good reason about why they might have chosen not to use an interface?

2 Answers

One possibility is due to dependency injection. Let's say there was an interface, it might look something like this:

public interface IStartup
{
    void ConfigureServices(IServiceCollection services);
    void Configure(IApplicationBuilder app);
}

However, the Configure method can take extra parameters as part of the dependency injection framework. For example I have an app here that looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //etc...
}

So it's now impossible to make this an interface because there could be any number of things passed in.

Additionally, the ConfigureServices is actually optional.

Finally, there actually does exist an interface called IStartup, but due to the above reasons, I've yet to see it used anywhere.

Bonus: You don't even need to have a startup class at all, all the work can be done when building the web host by calling ConfigureServices and Configure methods.

Besides for the reasons @DavidG pointed out, it is also possible to use startup method conventions to adjust registration of services and middleware based on the environment the application is hosted in.

For example, you can add this method beside the regular ConfigureServices method and it will only be called when running in the Staging environment:

public void ConfigureStagingServices(IServiceCollection services)
{
    // ...
}

The same conventions works for Configure(IApplicationBuilder app). See the documentation for further reference.

Related