| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using System; |
| | 5 | | using System.Runtime.ExceptionServices; |
| | 6 | | using Azure.Core; |
| | 7 | |
|
| | 8 | | namespace Microsoft.Extensions.Azure |
| | 9 | | { |
| | 10 | | internal class ClientRegistration<TClient, TOptions> |
| | 11 | | { |
| 172 | 12 | | public string Name { get; set; } |
| 48 | 13 | | public object Version { get; set; } |
| 96 | 14 | | public bool RequiresTokenCredential { get; set; } |
| | 15 | |
|
| | 16 | | private readonly Func<TOptions, TokenCredential, TClient> _factory; |
| | 17 | |
|
| 50 | 18 | | private readonly object _cacheLock = new object(); |
| | 19 | |
|
| | 20 | | private TClient _cachedClient; |
| | 21 | |
|
| | 22 | | private ExceptionDispatchInfo _cachedException; |
| | 23 | |
|
| 50 | 24 | | public ClientRegistration(string name, Func<TOptions, TokenCredential, TClient> factory) |
| | 25 | | { |
| 50 | 26 | | Name = name; |
| 50 | 27 | | _factory = factory; |
| 50 | 28 | | } |
| | 29 | |
|
| | 30 | | public TClient GetClient(TOptions options, TokenCredential tokenCredential) |
| | 31 | | { |
| 50 | 32 | | _cachedException?.Throw(); |
| | 33 | |
|
| 48 | 34 | | if (_cachedClient != null) |
| | 35 | | { |
| 2 | 36 | | return _cachedClient; |
| | 37 | | } |
| | 38 | |
|
| 46 | 39 | | lock (_cacheLock) |
| | 40 | | { |
| 46 | 41 | | _cachedException?.Throw(); |
| | 42 | |
|
| 46 | 43 | | if (_cachedClient != null) |
| | 44 | | { |
| 0 | 45 | | return _cachedClient; |
| | 46 | | } |
| | 47 | |
|
| | 48 | |
|
| 46 | 49 | | if (RequiresTokenCredential && tokenCredential == null) |
| | 50 | | { |
| 2 | 51 | | throw new InvalidOperationException("Client registration requires a TokenCredential. Configure it us |
| | 52 | | } |
| | 53 | |
|
| | 54 | | try |
| | 55 | | { |
| 44 | 56 | | _cachedClient = _factory(options, tokenCredential); |
| 42 | 57 | | } |
| 2 | 58 | | catch (Exception e) |
| | 59 | | { |
| 2 | 60 | | _cachedException = ExceptionDispatchInfo.Capture(e); |
| 2 | 61 | | throw; |
| | 62 | | } |
| | 63 | |
|
| 42 | 64 | | return _cachedClient; |
| | 65 | | } |
| 42 | 66 | | } |
| | 67 | | } |
| | 68 | | } |