How many overloads of 'Configure' method are possible in asp.net core?

Viewed 1725

The Configure method is working like magic in ASP.NET Core 3.1.

Scenario 1

When a new project is created, the framework scaffolds the following method signature:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

No surprises that the application works with this signature, because I can presume that the ASP.NET Core framework expects the signature to be as is.

Scenario 2

The second parameter IWebHostEnvironment is removed:

public void Configure(IApplicationBuilder app)

Application works.

Scenario 3

Injected my DbContext added to IServiceCollection in 'ConfigureServices' method along with logger:

public void Configure(IApplicationBuilder app, ILogger<Startup> logger, VegaDbContext vegaDbContext)

Surprisingly, application works. Looks like the framework is capable enough to resolve types added to service collection. Good sign.

Inline is implementation of ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<VegaDbContext>(options =>
            options.UseSqlServer(
                configuration.GetConnectionString("VegaDb")));
    services.AddControllers();
}

Scenario 4

Injected the WeatherForecastController, which I presume gets added to IServiceCollection via services.AddControllers():

public void Configure(IApplicationBuilder app, WeatherForecastController weatherForecastController)

Application does not work. The following exception is thrown:

System.Exception: 'Could not resolve a service of type 'Vega.Controllers.WeatherForecastController' for the parameter 'weatherForecastController' of method 'Configure' on type 'Vega.Startup'.'

Can some one explain how the method invocation is actually done by the framework and how it is capable of resolving few types like the ILogger and VegaDbContext but not the WeatherForecastController.

1 Answers

It works by using the dependency injection infrastructure. The arguments to Configure are retrieved from the web host's ServiceProvider. The keyword here is "service"--by default controllers are not added as services to the service collection.

In order to access controllers via dependency injection you need to call the AddControllersAsServices extension method for IMvcCoreBuilder or IMvcBuilder in your ConfigureServices method.

services.AddControllers()
        .AddControllersAsServices();
// or
services.AddControllersWithViews() 
        .AddControllersAsServices();
// or
services.AddMvc()
        .AddControllersAsServices();
Related