How To Implement DI In Middleware Dot Net Core

Author : Sachin Sharma
Published On : 08 May 2024
Tags: dotnet-core c#

In this Article I will explain how to implement dependency injection in middleware with example.

public class CustomAuthMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IUserService _userService;
        public CustomAuthMiddleware(RequestDelegate next, IUserService userService)
        {
            _next = next;
            _userService = userService;
        }
        public async Task Invoke(HttpContext context)
        {
            string token = context.Request.Headers["Authorization"];
            var userData = _userService.GetUserDetail(token);
        }
    }

I used user service interface in Invoke CustomAuthMiddleware constuctor as usaually do but this error occur.
Getting error
 

An error occurred while starting the application.
InvalidOperationException: Cannot resolve scoped service
IUserService from root provider.

 
Solution
 
Middleware is constructed at app startup. This is a standard error saying that you can't take a scoped dependency into a singleton class.
 
do not inject IUserService in middleware class construction
 
Inject IUserService in Invoke method.
 
public async Task Invoke(HttpContext context,IUserService _userService)
        {
          string token = context.Request.Headers["Authorization"];
           var userData=_userService.GetUserDetail(token);
         }
 
This solve my problem i hope that would help you also.
 
Comments

No comments have been added to this article.

Add Comment