Why do I get this InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.RequestDelegate'?

Rowan Freeman

I've just upgraded my ASP.NET Core WebApi project from .NET Core 2.2 to 3.1.

I've fixed up all of the compile-time errors, upgraded my Nuget packages, and I can now run the app.

However, When I call Build() on my IHostBuilder, I get the following exception:

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.RequestDelegate' while attempting to activate 'MyProject.Api.Middleware.ExceptionHandlerMiddleware'.

InvalidOperationException

The Middleware it's referring to is pretty standard.

ExceptionHandlerMiddleware.cs

public class ExceptionHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionHandlerMiddleware> _logger;

    public ExceptionHandlerMiddleware(RequestDelegate next, ILogger<ExceptionHandlerMiddleware> logger)
    {
        _logger = logger;
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        // redacted
    }
}

The rest of my app initialisation is fairly standard and I didn't change much going from 2.2 to 3.1 (2.2 was working).

I did change from services.AddMvc() to services.AddControllers().

Program.cs

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

    private static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseSerilog().UseStartup<Startup>();
            })
            .ConfigureLogging((context, logging) =>
            {
                logging
                .AddConfiguration(context.Configuration.GetSection("Logging"))
                .AddConsole()
                .AddDebug();
            });
    }
}

It's also worth mentioning that the ConfigureServices() method in Startup.cs is being called and runs fine, but Configure() never runs. The Build() method always kills the app before it gets to Configure().

My Startup's Configure method signature looks like this:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
Rowan Freeman

The solution for this problem contains two main elements:

  1. .NET Core 3.0 introduced a change regarding service provider validation.
  2. My code is registering too many classes, causing the validation to fail.

The solution to my problem was to introduce the following code in Program.cs:

private static IHostBuilder CreateHostBuilder(string[] args)
{
    return Host.CreateDefaultBuilder(args)
        .UseDefaultServiceProvider(opt =>
        {
            // this overrides the default service provider options
            // so that it doesn't validate the service collection (which raises exceptions)
        })
        [ ... ]
}

Thanks to other answers that directed my attention to my Startup.cs.

Full explanation

I use Scrutor to scan assemblies and auto-register classes. Scrutor is finding and registering my Middleware classes such as ExceptionHandlerMiddleware.

It was doing this in .NET Core 2.2 as well as 3.1. So why did it only break in Core 3.1?

Because .NET Core 3.0 introduced the Generic Host as the new default way to build a host.

The code now contains a part to enable ValidateOnBuild by default under the development environment. This caused my ServiceProvider to validate on build. And it couldn't resolve RequestDelegate because I didn't register that.

.UseDefaultServiceProvider((context, options) =>
{
    var isDevelopment = context.HostingEnvironment.IsDevelopment();
    options.ValidateScopes = isDevelopment;
    options.ValidateOnBuild = isDevelopment;
});

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

このInvalidOperationExceptionが発生するのはなぜですか:タイプ 'Microsoft.AspNetCore.Http.RequestDelegate'のサービスを解決できませんか?

分類Dev

Unable to resolve service for type 'System.Net.Http.HttpClient'

分類Dev

Unable to resolve service for type in ApplicationDbContext

分類Dev

Unable to resolve service for type 'System.Net.Http.HttpClient' using DI

分類Dev

Why do I get the error of unable to cast object

分類Dev

Unable to resolve host for http connection

分類Dev

InvalidOperationException Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)

分類Dev

Why do I get 'unknown type name DetailViewController' error, only some of the time when I compile?

分類Dev

Why do I get this NullExceptionError?

分類Dev

Why do I get a deadlock?

分類Dev

メソッドが見つかりません: 'Microsoft.Extensions.Primitives.StringValues Microsoft.AspNetCore.Http.IQueryCollection.get_Item(System.String)

分類Dev

Why do I get a type deduction error for a lambda returning lambda with multiple return paths?

分類Dev

Why do I get "incompatible pointer type" when assigning pointers to a multidimensional array

分類Dev

Could not load type 'Context' from assembly 'Microsoft.AspNetCore.Hosting'

分類Dev

AngularJS $ http.get with resolve

分類Dev

Why do I get: "preserveIconSpacing is private" error

分類Dev

Why do I get 0 as a result?

分類Dev

Why do I get a 404 on this REST tutorial?

分類Dev

Why do I get an error in this ListView creation?

分類Dev

Why do i get an empty bitmap?

分類Dev

Why do I get a parse error on '='

分類Dev

Why do I get Illegal number: {1..3}

分類Dev

Why do I get a 'NameError' with this import?

分類Dev

Why do I get remove used apps?

分類Dev

How do I get the stepContext from the PromptValidator in Microsoft Bot Framework?

分類Dev

Unable to resolve dependency in android studio, why this happen?

分類Dev

Cannot resolve scoped service from root provider when "ASPNETCORE_ENVIRONMENT": "Development"

分類Dev

Why I can't get Symfony Finder like a service?

分類Dev

Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2ConnectionErrorException

Related 関連記事

  1. 1

    このInvalidOperationExceptionが発生するのはなぜですか:タイプ 'Microsoft.AspNetCore.Http.RequestDelegate'のサービスを解決できませんか?

  2. 2

    Unable to resolve service for type 'System.Net.Http.HttpClient'

  3. 3

    Unable to resolve service for type in ApplicationDbContext

  4. 4

    Unable to resolve service for type 'System.Net.Http.HttpClient' using DI

  5. 5

    Why do I get the error of unable to cast object

  6. 6

    Unable to resolve host for http connection

  7. 7

    InvalidOperationException Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)

  8. 8

    Why do I get 'unknown type name DetailViewController' error, only some of the time when I compile?

  9. 9

    Why do I get this NullExceptionError?

  10. 10

    Why do I get a deadlock?

  11. 11

    メソッドが見つかりません: 'Microsoft.Extensions.Primitives.StringValues Microsoft.AspNetCore.Http.IQueryCollection.get_Item(System.String)

  12. 12

    Why do I get a type deduction error for a lambda returning lambda with multiple return paths?

  13. 13

    Why do I get "incompatible pointer type" when assigning pointers to a multidimensional array

  14. 14

    Could not load type 'Context' from assembly 'Microsoft.AspNetCore.Hosting'

  15. 15

    AngularJS $ http.get with resolve

  16. 16

    Why do I get: "preserveIconSpacing is private" error

  17. 17

    Why do I get 0 as a result?

  18. 18

    Why do I get a 404 on this REST tutorial?

  19. 19

    Why do I get an error in this ListView creation?

  20. 20

    Why do i get an empty bitmap?

  21. 21

    Why do I get a parse error on '='

  22. 22

    Why do I get Illegal number: {1..3}

  23. 23

    Why do I get a 'NameError' with this import?

  24. 24

    Why do I get remove used apps?

  25. 25

    How do I get the stepContext from the PromptValidator in Microsoft Bot Framework?

  26. 26

    Unable to resolve dependency in android studio, why this happen?

  27. 27

    Cannot resolve scoped service from root provider when "ASPNETCORE_ENVIRONMENT": "Development"

  28. 28

    Why I can't get Symfony Finder like a service?

  29. 29

    Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2ConnectionErrorException

ホットタグ

アーカイブ