EF. The connection was not closed. Connecting current state is connecting

I have jwt auth:

var messageHandlers = new JwtMessageHandler(_serviceProvider);

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    Events = new JwtBearerEvents
    {
        OnMessageReceived = messageHandlers.OnMessageReceived,
    },
    TokenValidationParameters = tokenValidationParameters
});

JwtMessageHandleris my custom handler. In the handler, I have to make several queries to the database, so I pass ServiceProviderand allow my user service:

public class JwtMessageHandler
{

        private IUserService _userService;  

        public async Task OnMessageReceived(MessageReceivedContext arg)
        {
             //parsing header, get claims from token
             ...
              _userService = (IUserService)arg.HttpContext.RequestServices.GetService(typeof(IUserService));
             var isRoleChanged = await _userService.IsRoleChanged(tokenObject.Subject, rolesFromToken);

            if (isRoleChanged)
            {
                GenerateBadResponse(arg);
                return;
            }

            var canLogin = await _userService.CanLogin(tokenObject.Subject);

            if (!canLogin)
            {
                GenerateBadResponse(arg);
                return;
            }
        }    
}

In the service, I make requests:

...
 var user = await _userManager.FindByEmailAsync(email);
 var currentRoles = await _userManager.GetRolesAsync(user);
..

OnMessageReceivedcalled for each request. When I have one request per page on the server, or I wait one or two seconds before doing something, everything works fine. But I have several pages on which I make 2-3 simultaneous requests to the server. And in this case, I get an error message:

The connection was not closed. The status of the current connection is connected to

I understand this problem with multithreading. JwtMessageHandlerIt is created once when the application starts. So, I put the line:

_userService = (IUserService)_serviceProvider.GetService(typeof(IUserService)); 

, . . , null _userService .

?

+4
2

, "" - - .

  • , IUserService "scope", (userManager, dbContext)
  • IServiceProvider, - " ". HttpContext.RequestServices .
  • , "" . , "" dbContext "".
  • JwtMessageHandler - / . _userService ( private IUserService _userService). OnMessageReceived (var _userService = ...).

(1), (2) (3). , (4) , .

+7

@ . MiddleWare .NETCORE. IUnitOfWork .

-

public Task Invoke(HttpContext context)
{
    _unitOfWork = (IUnitOfWork)context.RequestServices.GetService(typeof(IUnitOfWork));

       //Some checks            

        var apiKey = context.Request.Headers["X-ApiKey"][0];

        var clientApp = _unitOfWork.ClientApplicationsRepository.Items.FirstOrDefault(s => s.ApiKey == apiKey);

     //Some other code...

    return _next(context);
}
0

Source: https://habr.com/ru/post/1664134/


All Articles