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:
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