Exemplo n.º 1
0
        public async Task <SessionContext> GetSessionContextAsync(User user, CancellationToken cancellationToken)
        {
            await _identityService.AddOrUpdateUserAsync(user, cancellationToken);

            SessionContext removedSession = null;

            if (!_sessionContexts.TryGetValue(user.Id, out var sessionContext))
            {
                lock (_syncRoot)
                {
                    if (!_sessionContexts.TryGetValue(user.Id, out sessionContext))
                    {
                        var scope = _lifetimeScope.BeginLifetimeScope(
                            typeof(SessionContext),
                            builder => { builder.RegisterInstance(user); });

                        sessionContext = scope.Resolve <SessionContext>();

                        sessionContext.Start(cancellationToken);

                        _sessionContexts.Add(user.Id, sessionContext);

                        _recentSessionContextsQueue.AddFirst(user.Id);
                        while (_recentSessionContextsQueue.Count > _maxActiveSessions)
                        {
                            var sessionId = _recentSessionContextsQueue.Last.Value;
                            _recentSessionContextsQueue.RemoveLast();
                            _sessionContexts.Remove(sessionId, out removedSession);
                        }
                    }
                }
            }

            if (removedSession != null)
            {
                await removedSession.Complete();
            }

            return(sessionContext);
        }