| | | 1 | | namespace ClientManager.Shared.Messaging; |
| | | 2 | | |
| | | 3 | | public class MessageContextAccessor : IMessageContextAccessor |
| | | 4 | | { |
| | 1 | 5 | | static readonly AsyncLocal<MessageContext?> _current = new(); |
| | | 6 | | |
| | | 7 | | public MessageContext GetOrCreateContext() |
| | | 8 | | { |
| | 5 | 9 | | Current ??= new MessageContext(Guid.NewGuid(), null, DateTimeOffset.UtcNow); |
| | 5 | 10 | | return Current; |
| | | 11 | | } |
| | | 12 | | |
| | | 13 | | public void SetCurrentContext(MessageContext context) |
| | | 14 | | { |
| | 0 | 15 | | Current = context; |
| | 0 | 16 | | } |
| | | 17 | | |
| | | 18 | | public void SetCausationId(Guid messageId) |
| | | 19 | | { |
| | 0 | 20 | | if (messageId == Guid.Empty) |
| | 0 | 21 | | throw new ArgumentNullException(nameof(messageId), "The provided causationId is an Empty Guid"); |
| | | 22 | | |
| | 0 | 23 | | Current ??= GetOrCreateContext(); |
| | | 24 | | |
| | 0 | 25 | | Current = new MessageContext(Current.CorrelationId, messageId, Current.Timestamp); |
| | 0 | 26 | | } |
| | | 27 | | |
| | | 28 | | public MessageContext? Current |
| | | 29 | | { |
| | 18 | 30 | | get => _current.Value; |
| | 5 | 31 | | private set => _current.Value = value; |
| | | 32 | | } |
| | | 33 | | |
| | | 34 | | public void ClearContext() |
| | | 35 | | { |
| | 4 | 36 | | _current.Value = null; |
| | 4 | 37 | | } |
| | | 38 | | } |