// Receives messages from the queue in a loop private static void ReceiveMessages() { // Register a OnMessage callback _queueClient.RegisterMessageHandler( async(message, token) => { // need to manually instantiate new context because DI in singleton will always resolve same context var ctx = new UniversalTennisContext(_options.Options); try { var eventRepo = new EventRepository(ctx); var resultEvent = JsonConvert.DeserializeObject <ResultEvent>(message.GetBody <string>()); resultEvent.InfoDoc = JsonConvert.SerializeObject(resultEvent.Info); await eventRepo.InsertResultEvent(resultEvent); _logger.LogInformation( $"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}"); await _queueClient.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception e) { await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken); _logger.LogError(e, "Failed to process result event"); } finally { ctx.Dispose(); } }, new MessageHandlerOptions(ExceptionHandler) { MaxConcurrentCalls = 1, AutoComplete = false }); }
// Receives messages from the queue in a loop private static void ReceiveMessages() { // Register a OnMessage callback _queueClient.RegisterMessageHandler( async(message, token) => { // need to manually instantiate new context because DI in singleton will always resolve same context var ctx = new UniversalTennisContext(_options.Options); try { var eventRepo = new EventRepository(ctx); var playerEvent = JsonConvert.DeserializeObject <PlayerEvent>(message.GetBody <string>()); playerEvent.InfoDoc = JsonConvert.SerializeObject(playerEvent.Info); await eventRepo.InsertPlayerEvent(playerEvent); // Process the message _logger.LogInformation( $"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}"); await _queueClient.CompleteAsync(message.SystemProperties.LockToken); } catch (Exception e) { _logger.LogError(e, "Failed to process player event"); // add to dead letters queue so message isn't lost await _queueClient.DeadLetterAsync(message.SystemProperties.LockToken); } finally { ctx.Dispose(); // Complete the message so that it is not received again. // This can be done only if the queueClient is opened in ReceiveMode.PeekLock mode. } }, new MessageHandlerOptions(ExceptionHandler) { MaxConcurrentCalls = 1, AutoComplete = false }); }