From dc83309db79d3998ab706dc6f1f9f064c83c0451 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 13 Aug 2023 18:03:08 +0100 Subject: [PATCH] perf(blog): cache users --- OliverBooth/Services/BlogUserService.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/OliverBooth/Services/BlogUserService.cs b/OliverBooth/Services/BlogUserService.cs index 09ed3ef..9b797eb 100644 --- a/OliverBooth/Services/BlogUserService.cs +++ b/OliverBooth/Services/BlogUserService.cs @@ -1,3 +1,4 @@ +using System.Collections.Concurrent; using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore; using OliverBooth.Data.Blog; @@ -10,6 +11,7 @@ namespace OliverBooth.Services; internal sealed class BlogUserService : IBlogUserService { private readonly IDbContextFactory _dbContextFactory; + private readonly ConcurrentDictionary _userCache = new(); /// /// Initializes a new instance of the class. @@ -25,8 +27,12 @@ internal sealed class BlogUserService : IBlogUserService /// public bool TryGetUser(Guid id, [NotNullWhen(true)] out IUser? user) { + if (_userCache.TryGetValue(id, out user)) return true; + using BlogContext context = _dbContextFactory.CreateDbContext(); user = context.Users.Find(id); + + if (user is not null) _userCache.TryAdd(id, user); return user is not null; } }