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