2023-08-13 17:03:08 +00:00
|
|
|
using System.Collections.Concurrent;
|
2023-08-12 19:13:47 +00:00
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
2023-08-13 16:33:54 +00:00
|
|
|
using OliverBooth.Data.Blog;
|
2023-08-12 19:13:47 +00:00
|
|
|
|
2023-08-13 16:33:54 +00:00
|
|
|
namespace OliverBooth.Services;
|
2023-08-12 19:13:47 +00:00
|
|
|
|
|
|
|
/// <summary>
|
2023-08-13 16:33:54 +00:00
|
|
|
/// Represents an implementation of <see cref="IBlogUserService" />.
|
2023-08-12 19:13:47 +00:00
|
|
|
/// </summary>
|
2023-08-13 16:33:54 +00:00
|
|
|
internal sealed class BlogUserService : IBlogUserService
|
2023-08-12 19:13:47 +00:00
|
|
|
{
|
|
|
|
private readonly IDbContextFactory<BlogContext> _dbContextFactory;
|
2023-08-13 17:03:08 +00:00
|
|
|
private readonly ConcurrentDictionary<Guid, IUser> _userCache = new();
|
2023-08-12 19:13:47 +00:00
|
|
|
|
|
|
|
/// <summary>
|
2023-08-13 16:33:54 +00:00
|
|
|
/// Initializes a new instance of the <see cref="BlogUserService" /> class.
|
2023-08-12 19:13:47 +00:00
|
|
|
/// </summary>
|
|
|
|
/// <param name="dbContextFactory">
|
|
|
|
/// The <see cref="IDbContextFactory{TContext}" /> used to create a <see cref="BlogContext" />.
|
|
|
|
/// </param>
|
2023-08-13 16:33:54 +00:00
|
|
|
public BlogUserService(IDbContextFactory<BlogContext> dbContextFactory)
|
2023-08-12 19:13:47 +00:00
|
|
|
{
|
|
|
|
_dbContextFactory = dbContextFactory;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <inheritdoc />
|
|
|
|
public bool TryGetUser(Guid id, [NotNullWhen(true)] out IUser? user)
|
|
|
|
{
|
2023-08-13 17:03:08 +00:00
|
|
|
if (_userCache.TryGetValue(id, out user)) return true;
|
|
|
|
|
2023-08-12 19:13:47 +00:00
|
|
|
using BlogContext context = _dbContextFactory.CreateDbContext();
|
|
|
|
user = context.Users.Find(id);
|
2023-08-13 17:03:08 +00:00
|
|
|
|
|
|
|
if (user is not null) _userCache.TryAdd(id, user);
|
2023-08-12 19:13:47 +00:00
|
|
|
return user is not null;
|
|
|
|
}
|
|
|
|
}
|