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

View File

@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis; using System.Diagnostics.CodeAnalysis;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using OliverBooth.Data.Blog; using OliverBooth.Data.Blog;
@ -10,6 +11,7 @@ namespace OliverBooth.Services;
internal sealed class BlogUserService : IBlogUserService internal sealed class BlogUserService : IBlogUserService
{ {
private readonly IDbContextFactory<BlogContext> _dbContextFactory; private readonly IDbContextFactory<BlogContext> _dbContextFactory;
private readonly ConcurrentDictionary<Guid, IUser> _userCache = new();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="BlogUserService" /> class. /// Initializes a new instance of the <see cref="BlogUserService" /> class.
@ -25,8 +27,12 @@ internal sealed class BlogUserService : IBlogUserService
/// <inheritdoc /> /// <inheritdoc />
public bool TryGetUser(Guid id, [NotNullWhen(true)] out IUser? user) public bool TryGetUser(Guid id, [NotNullWhen(true)] out IUser? user)
{ {
if (_userCache.TryGetValue(id, out user)) return true;
using BlogContext context = _dbContextFactory.CreateDbContext(); using BlogContext context = _dbContextFactory.CreateDbContext();
user = context.Users.Find(id); user = context.Users.Find(id);
if (user is not null) _userCache.TryAdd(id, user);
return user is not null; return user is not null;
} }
} }