C# 10 - Difficulty with Custom Middleware and Dependency Injection in ASP.NET Core 6.0
I've searched everywhere and can't find a clear answer. I'm working on a project and hit a roadblock. I'm trying to figure out I'm working with an scenario with my custom middleware in an ASP.NET Core 6.0 application. I created a middleware to log requests and responses and inject additional dependencies using DI. However, I keep receiving an `InvalidOperationException` stating that 'No service for type 'MyService' has been registered'. Here's my middleware setup: ```csharp public class LoggingMiddleware { private readonly RequestDelegate _next; private readonly MyService _myService; public LoggingMiddleware(RequestDelegate next, MyService myService) { _next = next; _myService = myService; } public async Task InvokeAsync(HttpContext context) { // Log request details var requestPath = context.Request.Path; Console.WriteLine($"Request: {requestPath}"); await _next(context); // Log response details Console.WriteLine($"Response: {context.Response.StatusCode}"); } } ``` In `Startup.cs`, I'm registering the middleware like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<LoggingMiddleware>(); // Other middleware registrations... } ``` I also have `MyService` configured in the DI container: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddSingleton<MyService>(); // Other service registrations... } ``` When I run the application, I get the `InvalidOperationException` behavior. I suspect the scenario might be related to how Iām injecting `MyService` into the middleware. I have tried both transient and singleton lifetimes for `MyService`, but the behavior continues. How can I correctly set up my middleware to utilize the service without working with this behavior? This is my first time working with C# 3.11. Thanks in advance! Thanks in advance! I'm on Windows 11 using the latest version of C#. Am I missing something obvious?