How to fix Unhandled Exception after adding UserActivityMiddleware 'Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1

zerubabel shimeles 20 Reputation points
2023-07-09T07:32:24.4733333+00:00

I had created UserActivityMiddleware for checking every user isActive or not before making any request and then I introduced in the program.cs after authentication and authorization like this app.UseMiddleware<UserActivityMiddleware>(). Then, when I tring to debug there is an unhandled exception in the app.Run();. I used asp.net core 6.

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | .NET | Other
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-07-10T06:00:21.2066667+00:00

    Hi @zerubabel shimeles

    UserManager<ApplicationUser> is (by default) registered as a scoped dependency, whereas your UserActivityMiddleware middleware is constructed at app startup (effectively making it a singleton). This is a fairly standard error saying that you can't take a scoped dependency into a singleton class.

    To solve this issue, you can inject the UserManager<ApplicationUser> into your Invoke method:

    For example:

        public class MyCustomMiddleware
        {
            private readonly RequestDelegate _next;
    
            public MyCustomMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            // UserManager is injected into InvokeAsync
            public async Task InvokeAsync(HttpContext httpContext, IMessageWriter svc, UserManager<IdentityUser> userManager)
            {
                svc.Write($"Custom middleware: {DateTime.Now.Ticks.ToString()}");
    
                if (httpContext.User.Identity.IsAuthenticated)
                {
    
                    var username = httpContext.User.Identity.Name;
    
                    var result = await userManager.FindByNameAsync(username);
    
                    svc.Write($"User ID: {username}; User Email: {result.NormalizedEmail}");
    
                }
    
    
                await _next(httpContext);
            }
        }
    

    The result as below:

    capture1


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.