perf(blog): cache users
This commit is contained in:
parent
bbc76bc305
commit
dc83309db7
@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user