microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.Apps/Contexts/Context.Accessor.cs
43lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using Microsoft.Teams.Api.Activities; |
| 5 | |
| 6 | namespace Microsoft.Teams.Apps; |
| 7 | |
| 8 | public partial interface IContext |
| 9 | { |
| 10 | /// <summary> |
| 11 | /// Accessor |
| 12 | /// |
| 13 | /// based on https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http/src/HttpContextAccessor.cs |
| 14 | /// </summary> |
| 15 | public class Accessor |
| 16 | { |
| 17 | private static readonly AsyncLocal<ContextHolder> _async = new(); |
| 18 | |
| 19 | public IContext<IActivity>? Value |
| 20 | { |
| 21 | get => _async.Value?.Context; |
| 22 | internal set |
| 23 | { |
| 24 | _async.Value?.Clear(); |
| 25 | |
| 26 | if (value is not null) |
| 27 | { |
| 28 | _async.Value = new() { Context = value }; |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | private sealed class ContextHolder |
| 34 | { |
| 35 | public IContext<IActivity>? Context { get; set; } |
| 36 | |
| 37 | public void Clear() |
| 38 | { |
| 39 | Context = null; |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | } |