|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.ComponentModel.Composition; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using GitHub.Models; |
| 7 | +using GitHub.Services; |
| 8 | +using Microsoft.VisualStudio.Shell; |
| 9 | + |
| 10 | +namespace GitHub.Factories |
| 11 | +{ |
| 12 | + [Export(typeof(IModelServiceFactory))] |
| 13 | + [PartCreationPolicy(CreationPolicy.Shared)] |
| 14 | + public sealed class ModelServiceFactory : IModelServiceFactory, IDisposable |
| 15 | + { |
| 16 | + readonly IApiClientFactory apiClientFactory; |
| 17 | + readonly IHostCacheFactory hostCacheFactory; |
| 18 | + readonly IAvatarProvider avatarProvider; |
| 19 | + readonly Dictionary<IConnection, ModelService> cache = new Dictionary<IConnection, ModelService>(); |
| 20 | + readonly SemaphoreSlim cacheLock = new SemaphoreSlim(1); |
| 21 | + |
| 22 | + [ImportingConstructor] |
| 23 | + public ModelServiceFactory( |
| 24 | + IApiClientFactory apiClientFactory, |
| 25 | + IHostCacheFactory hostCacheFactory, |
| 26 | + IAvatarProvider avatarProvider) |
| 27 | + { |
| 28 | + this.apiClientFactory = apiClientFactory; |
| 29 | + this.hostCacheFactory = hostCacheFactory; |
| 30 | + this.avatarProvider = avatarProvider; |
| 31 | + } |
| 32 | + |
| 33 | + public async Task<IModelService> CreateAsync(IConnection connection) |
| 34 | + { |
| 35 | + ModelService result; |
| 36 | + |
| 37 | + await cacheLock.WaitAsync(); |
| 38 | + |
| 39 | + try |
| 40 | + { |
| 41 | + if (!cache.TryGetValue(connection, out result)) |
| 42 | + { |
| 43 | + result = new ModelService( |
| 44 | + await apiClientFactory.Create(connection.HostAddress), |
| 45 | + await hostCacheFactory.Create(connection.HostAddress), |
| 46 | + avatarProvider); |
| 47 | + } |
| 48 | + } |
| 49 | + finally |
| 50 | + { |
| 51 | + cacheLock.Release(); |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | + } |
| 56 | + |
| 57 | + public IModelService CreateBlocking(IConnection connection) |
| 58 | + { |
| 59 | + return ThreadHelper.JoinableTaskFactory.Run(() => CreateAsync(connection)); |
| 60 | + } |
| 61 | + |
| 62 | + public void Dispose() => cacheLock.Dispose(); |
| 63 | + } |
| 64 | +} |
0 commit comments