perf(blog): cache users

This commit is contained in:
Oliver Booth 2023-08-13 18:03:08 +01:00
parent bbc76bc305
commit dc83309db7
Signed by: oliverbooth
GPG Key ID: B89D139977693FED
1 changed files with 6 additions and 0 deletions

View File

@ -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<BlogContext> _dbContextFactory;
private readonly ConcurrentDictionary<Guid, IUser> _userCache = new();
/// <summary>
/// Initializes a new instance of the <see cref="BlogUserService" /> class.
@ -25,8 +27,12 @@ internal sealed class BlogUserService : IBlogUserService
/// <inheritdoc />
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;
}
}