From 899217480b13cbba540f593a6811111170adf55d Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:08:38 +0100 Subject: [PATCH 01/10] feat(infrastructure): add keyed cache example --- README.md | 2 + ...multiple-infrastructure-implementations.md | 21 +++++++++ .../Implementations/InMemoryCacheAdapter.cs | 20 +++++++++ .../Implementations/RedisCacheAdapter.cs | 20 +++++++++ .../InfrastructureServiceRegistration.cs | 5 +++ .../Interfaces/ICacheRepository.cs | 9 ++++ .../KeyedCacheRepositoryTests.cs | 44 +++++++++++++++++++ 7 files changed, 121 insertions(+) create mode 100644 docs/multiple-infrastructure-implementations.md create mode 100644 src/ModularNet.Infrastructure/Implementations/InMemoryCacheAdapter.cs create mode 100644 src/ModularNet.Infrastructure/Implementations/RedisCacheAdapter.cs create mode 100644 src/ModularNet.Infrastructure/Interfaces/ICacheRepository.cs create mode 100644 src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs diff --git a/README.md b/README.md index 89b047b..01bc12c 100644 --- a/README.md +++ b/README.md @@ -40,3 +40,5 @@ All architectural rules, layer responsibilities, differences from Onion Architec - **[Coding Standards](coding-standards.md):** Architecture rules, conventions, and step-by-step feature guide. - **[Wiki](https://github.com/ale206/ModularNet/wiki):** Component-by-component reference for the solution. - **[Discussions](https://github.com/ale206/ModularNet/discussions):** Ideas, questions, and feedback. Contributions and Pull Requests are welcome! + +For an example of selecting one or multiple infrastructure implementations, see [Multiple infrastructure implementations](docs/multiple-infrastructure-implementations.md). diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md new file mode 100644 index 0000000..f090f34 --- /dev/null +++ b/docs/multiple-infrastructure-implementations.md @@ -0,0 +1,21 @@ +# Multiple infrastructure implementations + +The cache registrations demonstrate one contract, `ICacheRepository`, backed by the existing in-memory and Redis repositories. `AddInfrastructureServices` registers each adapter with a `CacheType` key. Both can be used in the same scope; Redis still requires its normal connection configuration. + +Inject a known backend into a Business class: + +```csharp +public ExampleManager( + [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository) +{ + _cacheRepository = cacheRepository; +} +``` + +Import `Microsoft.Extensions.DependencyInjection`, `ModularNet.Domain.Enums`, and `ModularNet.Infrastructure.Interfaces`. Use `CacheType.Redis` for Redis. For a single backend, register only that implementation, and inject it with its key; alternatively register it unkeyed and inject `ICacheRepository` normally. For runtime selection, resolve the requested key within the current DI scope with `GetRequiredKeyedService(cacheType)`. An unknown or unregistered key fails rather than silently selecting another backend. Avoid resolving scoped services from the root provider. + +To add a backend, implement the contract, register it with a distinct key and appropriate lifetime, and test all contract operations. Do not register multiple unkeyed implementations expecting ordinary injection to select between them: .NET resolves the last registration for a single service; `IEnumerable` returns all unkeyed registrations. + +The adapters preserve the existing cache API and lifetimes. They are an example of selection, not database provider implementations. To add PostgreSQL or another database, implement provider-specific repositories and SQL, connection factory, and transaction handling; select a consistent set together. The current MySQL repositories contain provider-specific SQL. Repositories participating in one unit of work must share the same scoped connection and transaction; keyed registration alone does not make cross-provider transactions atomic. Test each provider against its actual database, including commit and rollback. + +Interfaces currently live in Infrastructure under the project's coding standards. Multiple implementations can coexist there in provider-specific folders. If provider dependencies or independent deployment justify separate projects, first move shared contracts to an Infrastructure abstractions project, then have Business and each provider project reference it; keep registration in the application composition root. This adds project and migration overhead, so the template keeps its existing layout until that separation is needed. diff --git a/src/ModularNet.Infrastructure/Implementations/InMemoryCacheAdapter.cs b/src/ModularNet.Infrastructure/Implementations/InMemoryCacheAdapter.cs new file mode 100644 index 0000000..c91da3c --- /dev/null +++ b/src/ModularNet.Infrastructure/Implementations/InMemoryCacheAdapter.cs @@ -0,0 +1,20 @@ +using ModularNet.Infrastructure.Interfaces; + +namespace ModularNet.Infrastructure.Implementations; + +public class InMemoryCacheAdapter : ICacheRepository +{ + private readonly IInMemoryCacheRepository _inMemoryCacheRepository; + + public InMemoryCacheAdapter(IInMemoryCacheRepository inMemoryCacheRepository) + { + _inMemoryCacheRepository = inMemoryCacheRepository; + } + + public Task Save(string key, T value, int expirationSeconds) => + _inMemoryCacheRepository.SaveToInMemoryCache(key, value, expirationSeconds); + + public Task Get(string key) => _inMemoryCacheRepository.GetFromInMemoryCache(key); + + public Task Remove(string key) => _inMemoryCacheRepository.RemoveFromInMemoryCache(key); +} diff --git a/src/ModularNet.Infrastructure/Implementations/RedisCacheAdapter.cs b/src/ModularNet.Infrastructure/Implementations/RedisCacheAdapter.cs new file mode 100644 index 0000000..f6c4db1 --- /dev/null +++ b/src/ModularNet.Infrastructure/Implementations/RedisCacheAdapter.cs @@ -0,0 +1,20 @@ +using ModularNet.Infrastructure.Interfaces; + +namespace ModularNet.Infrastructure.Implementations; + +public class RedisCacheAdapter : ICacheRepository +{ + private readonly IRedisRepository _redisRepository; + + public RedisCacheAdapter(IRedisRepository redisRepository) + { + _redisRepository = redisRepository; + } + + public Task Save(string key, T value, int expirationSeconds) => + _redisRepository.SaveToRedisCache(key, value, expirationSeconds); + + public Task Get(string key) => _redisRepository.GetFromRedisCache(key); + + public Task Remove(string key) => _redisRepository.RemoveFromRedisCache(key); +} diff --git a/src/ModularNet.Infrastructure/InfrastructureServiceRegistration.cs b/src/ModularNet.Infrastructure/InfrastructureServiceRegistration.cs index a52a699..8138a1e 100644 --- a/src/ModularNet.Infrastructure/InfrastructureServiceRegistration.cs +++ b/src/ModularNet.Infrastructure/InfrastructureServiceRegistration.cs @@ -1,5 +1,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using ModularNet.Domain.Enums; using ModularNet.Infrastructure.Implementations; using ModularNet.Infrastructure.Interfaces; @@ -25,6 +26,10 @@ public static IServiceCollection AddInfrastructureServices(this IServiceCollecti services.AddSingleton(); services.AddScoped(); + // A shared contract can expose one or more backends without registration-order selection. + services.AddKeyedScoped(CacheType.InMemory); + services.AddKeyedScoped(CacheType.Redis); + // HttpClient Services with Firebase services.AddHttpClient((sp, httpClient) => { diff --git a/src/ModularNet.Infrastructure/Interfaces/ICacheRepository.cs b/src/ModularNet.Infrastructure/Interfaces/ICacheRepository.cs new file mode 100644 index 0000000..95b2e73 --- /dev/null +++ b/src/ModularNet.Infrastructure/Interfaces/ICacheRepository.cs @@ -0,0 +1,9 @@ +namespace ModularNet.Infrastructure.Interfaces; + +/// A common contract for selecting a cache backend through keyed dependency injection. +public interface ICacheRepository +{ + Task Save(string key, T value, int expirationSeconds); + Task Get(string key); + Task Remove(string key); +} diff --git a/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs b/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs new file mode 100644 index 0000000..4bdb222 --- /dev/null +++ b/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs @@ -0,0 +1,44 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using ModularNet.Domain.Enums; +using ModularNet.Infrastructure; +using ModularNet.Infrastructure.Interfaces; +using Moq; +using Xunit; + +namespace ModularNet.UnitTests; + +public class KeyedCacheRepositoryTests +{ + [Fact] + public async Task KeyedRepositoriesDispatchToTheirOwnBackends() + { + var inMemoryCacheRepositoryMock = new Mock(); + var redisRepositoryMock = new Mock(); + inMemoryCacheRepositoryMock.Setup(repository => repository.GetFromInMemoryCache("key")) + .ReturnsAsync("memory"); + redisRepositoryMock.Setup(repository => repository.GetFromRedisCache("key")) + .ReturnsAsync("redis"); + + var serviceCollection = new ServiceCollection(); + serviceCollection.AddInfrastructureServices(new ConfigurationBuilder().Build()); + serviceCollection.AddSingleton(inMemoryCacheRepositoryMock.Object); + serviceCollection.AddScoped(_ => redisRepositoryMock.Object); + using var serviceProvider = serviceCollection.BuildServiceProvider(); + using var serviceScope = serviceProvider.CreateScope(); + var inMemoryCacheRepository = serviceScope.ServiceProvider.GetRequiredKeyedService(CacheType.InMemory); + var redisCacheRepository = serviceScope.ServiceProvider.GetRequiredKeyedService(CacheType.Redis); + + await inMemoryCacheRepository.Save("key", "value", 30); + await redisCacheRepository.Save("key", "value", 30); + Assert.Equal("memory", await inMemoryCacheRepository.Get("key")); + Assert.Equal("redis", await redisCacheRepository.Get("key")); + await inMemoryCacheRepository.Remove("key"); + await redisCacheRepository.Remove("key"); + + inMemoryCacheRepositoryMock.Verify(repository => repository.SaveToInMemoryCache("key", "value", 30), Times.Once); + redisRepositoryMock.Verify(repository => repository.SaveToRedisCache("key", "value", 30), Times.Once); + inMemoryCacheRepositoryMock.Verify(repository => repository.RemoveFromInMemoryCache("key"), Times.Once); + redisRepositoryMock.Verify(repository => repository.RemoveFromRedisCache("key"), Times.Once); + } +} From bfe70c8ac67cc76526a5f02e7f85d85a2c4f9e20 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:44:41 +0100 Subject: [PATCH 02/10] feat(cache): use keyed adapter in settings --- ...multiple-infrastructure-implementations.md | 6 ++++- .../Implementations/UsersSettingsManager.cs | 15 ++++++------ .../KeyedCacheRepositoryTests.cs | 23 +++++++++++++++++++ .../UsersSettingsManagerTests.cs | 16 ++++++------- 4 files changed, 44 insertions(+), 16 deletions(-) diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md index f090f34..b5c8614 100644 --- a/docs/multiple-infrastructure-implementations.md +++ b/docs/multiple-infrastructure-implementations.md @@ -2,7 +2,7 @@ The cache registrations demonstrate one contract, `ICacheRepository`, backed by the existing in-memory and Redis repositories. `AddInfrastructureServices` registers each adapter with a `CacheType` key. Both can be used in the same scope; Redis still requires its normal connection configuration. -Inject a known backend into a Business class: +`UsersSettingsManager` injects the in-memory adapter as a working example. Inject a known backend into a Business class: ```csharp public ExampleManager( @@ -19,3 +19,7 @@ To add a backend, implement the contract, register it with a distinct key and ap The adapters preserve the existing cache API and lifetimes. They are an example of selection, not database provider implementations. To add PostgreSQL or another database, implement provider-specific repositories and SQL, connection factory, and transaction handling; select a consistent set together. The current MySQL repositories contain provider-specific SQL. Repositories participating in one unit of work must share the same scoped connection and transaction; keyed registration alone does not make cross-provider transactions atomic. Test each provider against its actual database, including commit and rollback. Interfaces currently live in Infrastructure under the project's coding standards. Multiple implementations can coexist there in provider-specific folders. If provider dependencies or independent deployment justify separate projects, first move shared contracts to an Infrastructure abstractions project, then have Business and each provider project reference it; keep registration in the application composition root. This adds project and migration overhead, so the template keeps its existing layout until that separation is needed. + +## Disabled cache behavior + +`AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. diff --git a/src/ModularNet.Business/Implementations/UsersSettingsManager.cs b/src/ModularNet.Business/Implementations/UsersSettingsManager.cs index 1fab7e2..27a19c9 100644 --- a/src/ModularNet.Business/Implementations/UsersSettingsManager.cs +++ b/src/ModularNet.Business/Implementations/UsersSettingsManager.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.DependencyInjection; using ModularNet.Business.Interfaces; using ModularNet.Domain.Entities; using ModularNet.Domain.Enums; @@ -8,14 +9,14 @@ namespace ModularNet.Business.Implementations; public class UsersSettingsManager : IUsersSettingsManager { - private readonly ICacheManager _cacheManager; + private readonly ICacheRepository _cacheRepository; private readonly IUnitOfWork _unitOfWork; private readonly IUsersSettingsRepository _usersSettingsRepository; - public UsersSettingsManager(IUsersSettingsRepository usersSettingsRepository, ICacheManager cacheManager, IUnitOfWork unitOfWork) + public UsersSettingsManager(IUsersSettingsRepository usersSettingsRepository, [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository, IUnitOfWork unitOfWork) { _usersSettingsRepository = usersSettingsRepository; - _cacheManager = cacheManager; + _cacheRepository = cacheRepository; _unitOfWork = unitOfWork; } @@ -25,7 +26,7 @@ public async Task> GetUserSettingsByUserId(Guid userId) var usrSettingsItem = $"{userId}-settings"; //TODO: Replicated. Set in config? Or in better place. var userSettingsFromCache = - await _cacheManager.GetFromCache>(usrSettingsItem, CacheType.InMemory); + await _cacheRepository.Get>(usrSettingsItem); if (userSettingsFromCache != null) return userSettingsFromCache; var userSettings = new List(); @@ -44,7 +45,7 @@ public async Task> GetUserSettingsByUserId(Guid userId) // Cache settings for one month. Cache will be invalidated when new settings are created or updated // TODO: Time is replicated in CreateOrUpdateUserSettings - await _cacheManager.SaveInCache(usrSettingsItem, userSettings, CacheType.InMemory, 2592000); + await _cacheRepository.Save(usrSettingsItem, userSettings, 2592000); return userSettings; } @@ -61,7 +62,7 @@ public async Task> CreateOrUpdateUserSettings( // Remove current settings from cache var usrSettingsItem = $"{userId}-settings"; //TODO: Replicated. Set in config? Or in better place. - await _cacheManager.RemoveFromCache(usrSettingsItem, CacheType.InMemory); + await _cacheRepository.Remove(usrSettingsItem); // Lists to track settings for update and creation var settingsToUpdate = new List(); @@ -116,7 +117,7 @@ public async Task> CreateOrUpdateUserSettings( // Cache settings for one month. Cache will be invalidated when new settings are created or updated // TODO: Time is replicated in GetUserSettings - await _cacheManager.SaveInCache(usrSettingsItem, allSettings, CacheType.InMemory, 2592000); + await _cacheRepository.Save(usrSettingsItem, allSettings, 2592000); // Return the updated user settings return allSettings; diff --git a/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs b/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs index 4bdb222..f78c881 100644 --- a/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs +++ b/src/ModularNet.UnitTests/KeyedCacheRepositoryTests.cs @@ -1,8 +1,11 @@ +using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using ModularNet.Domain.Enums; using ModularNet.Infrastructure; using ModularNet.Infrastructure.Interfaces; +using ModularNet.Infrastructure.Implementations; using Moq; using Xunit; @@ -41,4 +44,24 @@ public async Task KeyedRepositoriesDispatchToTheirOwnBackends() inMemoryCacheRepositoryMock.Verify(repository => repository.RemoveFromInMemoryCache("key"), Times.Once); redisRepositoryMock.Verify(repository => repository.RemoveFromRedisCache("key"), Times.Once); } + [Fact] + public async Task DisabledRedisAdapterTreatsReadsAsMissesWithoutConnecting() + { + var redisConnectionFactoryMock = new Mock(MockBehavior.Strict); + var loggerMock = new Mock>(); + var hostingEnvironmentMock = new Mock(); + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["AppSettings:ModularNetConfig:RedisCacheEnabled"] = "false" + }).Build(); + var redisRepository = new RedisRepository(redisConnectionFactoryMock.Object, loggerMock.Object, + hostingEnvironmentMock.Object, configuration); + var redisCacheAdapter = new RedisCacheAdapter(redisRepository); + + await redisCacheAdapter.Save("key", "value", 30); + Assert.Null(await redisCacheAdapter.Get("key")); + await redisCacheAdapter.Remove("key"); + redisConnectionFactoryMock.VerifyNoOtherCalls(); + } + } diff --git a/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs b/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs index 62a3ba5..5d27a96 100644 --- a/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs +++ b/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs @@ -11,7 +11,7 @@ namespace ModularNet.UnitTests; public class UsersSettingsManagerTests { - private readonly Mock _cacheManagerMock = new(); + private readonly Mock _cacheRepositoryMock = new(); private readonly Mock _unitOfWorkMock = new(); private readonly Mock _usersSettingsRepositoryMock = new(); @@ -19,7 +19,7 @@ private UsersSettingsManager CreateUsersSettingsManager() { return new UsersSettingsManager( _usersSettingsRepositoryMock.Object, - _cacheManagerMock.Object, + _cacheRepositoryMock.Object, _unitOfWorkMock.Object); } @@ -30,8 +30,8 @@ public async Task GetUserSettingsByUserIdReturnsFromCacheWhenPresent() var usersSettingsManager = CreateUsersSettingsManager(); var userId = Guid.NewGuid(); var cachedSettings = new List { UserSettingsHelper.GetUserSetting() }; - _cacheManagerMock - .Setup(x => x.GetFromCache>($"{userId}-settings", CacheType.InMemory)) + _cacheRepositoryMock + .Setup(x => x.Get>($"{userId}-settings")) .ReturnsAsync(cachedSettings); // Act @@ -50,8 +50,8 @@ public async Task GetUserSettingsByUserIdFetchesFromRepositoryAndCachesWhenCache var userId = Guid.NewGuid(); var settingDto = UserSettingsHelper.GetUserSettingDto(); settingDto.UserId = userId; - _cacheManagerMock - .Setup(x => x.GetFromCache>($"{userId}-settings", CacheType.InMemory)) + _cacheRepositoryMock + .Setup(x => x.Get>($"{userId}-settings")) .ReturnsAsync((List?)null); _usersSettingsRepositoryMock .Setup(x => x.GetUserSettings(userId)) @@ -63,8 +63,8 @@ public async Task GetUserSettingsByUserIdFetchesFromRepositoryAndCachesWhenCache // Assert Assert.Single(userSettings); Assert.Equal(settingDto.SettingName, userSettings[0].SettingName); - _cacheManagerMock.Verify( - x => x.SaveInCache($"{userId}-settings", It.IsAny>(), CacheType.InMemory, 2592000), + _cacheRepositoryMock.Verify( + x => x.Save($"{userId}-settings", It.IsAny>(), 2592000), Times.Once); } From 29bc4ad1ae1335bf700308f5c72bb81f2ffc7d5f Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:45:51 +0100 Subject: [PATCH 03/10] fix(cache): preserve manager boundaries --- ...multiple-infrastructure-implementations.md | 6 ++-- .../Implementations/CacheManager.cs | 36 ++++++------------- .../Implementations/UsersSettingsManager.cs | 15 ++++---- src/ModularNet.UnitTests/CacheManagerTests.cs | 5 +-- .../UsersSettingsManagerTests.cs | 16 ++++----- 5 files changed, 32 insertions(+), 46 deletions(-) diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md index b5c8614..8d941e0 100644 --- a/docs/multiple-infrastructure-implementations.md +++ b/docs/multiple-infrastructure-implementations.md @@ -2,10 +2,10 @@ The cache registrations demonstrate one contract, `ICacheRepository`, backed by the existing in-memory and Redis repositories. `AddInfrastructureServices` registers each adapter with a `CacheType` key. Both can be used in the same scope; Redis still requires its normal connection configuration. -`UsersSettingsManager` injects the in-memory adapter as a working example. Inject a known backend into a Business class: +`CacheManager` injects both keyed adapters and selects one using `CacheType`. Other managers use `ICacheManager`, as in `UsersSettingsManager`. To inject a known backend into its corresponding manager: ```csharp -public ExampleManager( +public CacheManager( [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository) { _cacheRepository = cacheRepository; @@ -22,4 +22,4 @@ Interfaces currently live in Infrastructure under the project's coding standards ## Disabled cache behavior -`AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. +`AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. diff --git a/src/ModularNet.Business/Implementations/CacheManager.cs b/src/ModularNet.Business/Implementations/CacheManager.cs index c895035..f0d0098 100644 --- a/src/ModularNet.Business/Implementations/CacheManager.cs +++ b/src/ModularNet.Business/Implementations/CacheManager.cs @@ -1,3 +1,4 @@ +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ModularNet.Business.Interfaces; using ModularNet.Domain.Enums; @@ -7,12 +8,12 @@ namespace ModularNet.Business.Implementations; public class CacheManager : ICacheManager { - private readonly IInMemoryCacheRepository _inMemoryCacheRepository; + private readonly ICacheRepository _inMemoryCacheRepository; private readonly ILogger _logger; - private readonly IRedisRepository _redisRepository; + private readonly ICacheRepository _redisRepository; - public CacheManager(ILogger logger, IInMemoryCacheRepository inMemoryCacheRepository, - IRedisRepository redisRepository) + public CacheManager(ILogger logger, [FromKeyedServices(CacheType.InMemory)] ICacheRepository inMemoryCacheRepository, + [FromKeyedServices(CacheType.Redis)] ICacheRepository redisRepository) { _logger = logger; _inMemoryCacheRepository = inMemoryCacheRepository; @@ -28,10 +29,10 @@ public async Task SaveInCache(string item, T value, CacheType cacheType, int switch (cacheType) { case CacheType.InMemory: - await _inMemoryCacheRepository.SaveToInMemoryCache(item, value, cacheExpirationSeconds); + await _inMemoryCacheRepository.Save(item, value, cacheExpirationSeconds); break; case CacheType.Redis: - await _redisRepository.SaveToRedisCache(item, value, cacheExpirationSeconds); + await _redisRepository.Save(item, value, cacheExpirationSeconds); break; default: throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); @@ -45,9 +46,9 @@ public async Task SaveInCache(string item, T value, CacheType cacheType, int switch (cacheType) { case CacheType.InMemory: - return await _inMemoryCacheRepository.GetFromInMemoryCache(itemKey); + return await _inMemoryCacheRepository.Get(itemKey); case CacheType.Redis: - return await _redisRepository.GetFromRedisCache(itemKey); + return await _redisRepository.Get(itemKey); default: throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); } @@ -60,29 +61,14 @@ public async Task RemoveFromCache(string item, CacheType cacheType) switch (cacheType) { case CacheType.InMemory: - await _inMemoryCacheRepository.RemoveFromInMemoryCache(item); + await _inMemoryCacheRepository.Remove(item); break; case CacheType.Redis: - await _redisRepository.RemoveFromRedisCache(item); + await _redisRepository.Remove(item); break; default: throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); } } - private async Task RemoveExpiredItems(CacheType cacheType) - { - _logger.LogDebug($"Start method {nameof(RemoveExpiredItems)}"); - - switch (cacheType) - { - case CacheType.InMemory: - await _inMemoryCacheRepository.RemoveExpiredItemsFromInMemoryCache(); - break; - case CacheType.Redis: - break; - default: - throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); - } - } } diff --git a/src/ModularNet.Business/Implementations/UsersSettingsManager.cs b/src/ModularNet.Business/Implementations/UsersSettingsManager.cs index 27a19c9..1fab7e2 100644 --- a/src/ModularNet.Business/Implementations/UsersSettingsManager.cs +++ b/src/ModularNet.Business/Implementations/UsersSettingsManager.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.DependencyInjection; using ModularNet.Business.Interfaces; using ModularNet.Domain.Entities; using ModularNet.Domain.Enums; @@ -9,14 +8,14 @@ namespace ModularNet.Business.Implementations; public class UsersSettingsManager : IUsersSettingsManager { - private readonly ICacheRepository _cacheRepository; + private readonly ICacheManager _cacheManager; private readonly IUnitOfWork _unitOfWork; private readonly IUsersSettingsRepository _usersSettingsRepository; - public UsersSettingsManager(IUsersSettingsRepository usersSettingsRepository, [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository, IUnitOfWork unitOfWork) + public UsersSettingsManager(IUsersSettingsRepository usersSettingsRepository, ICacheManager cacheManager, IUnitOfWork unitOfWork) { _usersSettingsRepository = usersSettingsRepository; - _cacheRepository = cacheRepository; + _cacheManager = cacheManager; _unitOfWork = unitOfWork; } @@ -26,7 +25,7 @@ public async Task> GetUserSettingsByUserId(Guid userId) var usrSettingsItem = $"{userId}-settings"; //TODO: Replicated. Set in config? Or in better place. var userSettingsFromCache = - await _cacheRepository.Get>(usrSettingsItem); + await _cacheManager.GetFromCache>(usrSettingsItem, CacheType.InMemory); if (userSettingsFromCache != null) return userSettingsFromCache; var userSettings = new List(); @@ -45,7 +44,7 @@ public async Task> GetUserSettingsByUserId(Guid userId) // Cache settings for one month. Cache will be invalidated when new settings are created or updated // TODO: Time is replicated in CreateOrUpdateUserSettings - await _cacheRepository.Save(usrSettingsItem, userSettings, 2592000); + await _cacheManager.SaveInCache(usrSettingsItem, userSettings, CacheType.InMemory, 2592000); return userSettings; } @@ -62,7 +61,7 @@ public async Task> CreateOrUpdateUserSettings( // Remove current settings from cache var usrSettingsItem = $"{userId}-settings"; //TODO: Replicated. Set in config? Or in better place. - await _cacheRepository.Remove(usrSettingsItem); + await _cacheManager.RemoveFromCache(usrSettingsItem, CacheType.InMemory); // Lists to track settings for update and creation var settingsToUpdate = new List(); @@ -117,7 +116,7 @@ public async Task> CreateOrUpdateUserSettings( // Cache settings for one month. Cache will be invalidated when new settings are created or updated // TODO: Time is replicated in GetUserSettings - await _cacheRepository.Save(usrSettingsItem, allSettings, 2592000); + await _cacheManager.SaveInCache(usrSettingsItem, allSettings, CacheType.InMemory, 2592000); // Return the updated user settings return allSettings; diff --git a/src/ModularNet.UnitTests/CacheManagerTests.cs b/src/ModularNet.UnitTests/CacheManagerTests.cs index 04def9c..975a805 100644 --- a/src/ModularNet.UnitTests/CacheManagerTests.cs +++ b/src/ModularNet.UnitTests/CacheManagerTests.cs @@ -3,6 +3,7 @@ using ModularNet.Business.Interfaces; using ModularNet.Domain.Enums; using ModularNet.Infrastructure.Interfaces; +using ModularNet.Infrastructure.Implementations; using Moq; namespace ModularNet.UnitTests; @@ -19,8 +20,8 @@ public class CacheManagerTests public CacheManagerTests() { - _cacheManager = new CacheManager(_loggerMock.Object, _inMemoryCacheRepositoryMock.Object, - _redisRepositoryMock.Object); + _cacheManager = new CacheManager(_loggerMock.Object, new InMemoryCacheAdapter(_inMemoryCacheRepositoryMock.Object), + new RedisCacheAdapter(_redisRepositoryMock.Object)); } [Fact] diff --git a/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs b/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs index 5d27a96..62a3ba5 100644 --- a/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs +++ b/src/ModularNet.UnitTests/UsersSettingsManagerTests.cs @@ -11,7 +11,7 @@ namespace ModularNet.UnitTests; public class UsersSettingsManagerTests { - private readonly Mock _cacheRepositoryMock = new(); + private readonly Mock _cacheManagerMock = new(); private readonly Mock _unitOfWorkMock = new(); private readonly Mock _usersSettingsRepositoryMock = new(); @@ -19,7 +19,7 @@ private UsersSettingsManager CreateUsersSettingsManager() { return new UsersSettingsManager( _usersSettingsRepositoryMock.Object, - _cacheRepositoryMock.Object, + _cacheManagerMock.Object, _unitOfWorkMock.Object); } @@ -30,8 +30,8 @@ public async Task GetUserSettingsByUserIdReturnsFromCacheWhenPresent() var usersSettingsManager = CreateUsersSettingsManager(); var userId = Guid.NewGuid(); var cachedSettings = new List { UserSettingsHelper.GetUserSetting() }; - _cacheRepositoryMock - .Setup(x => x.Get>($"{userId}-settings")) + _cacheManagerMock + .Setup(x => x.GetFromCache>($"{userId}-settings", CacheType.InMemory)) .ReturnsAsync(cachedSettings); // Act @@ -50,8 +50,8 @@ public async Task GetUserSettingsByUserIdFetchesFromRepositoryAndCachesWhenCache var userId = Guid.NewGuid(); var settingDto = UserSettingsHelper.GetUserSettingDto(); settingDto.UserId = userId; - _cacheRepositoryMock - .Setup(x => x.Get>($"{userId}-settings")) + _cacheManagerMock + .Setup(x => x.GetFromCache>($"{userId}-settings", CacheType.InMemory)) .ReturnsAsync((List?)null); _usersSettingsRepositoryMock .Setup(x => x.GetUserSettings(userId)) @@ -63,8 +63,8 @@ public async Task GetUserSettingsByUserIdFetchesFromRepositoryAndCachesWhenCache // Assert Assert.Single(userSettings); Assert.Equal(settingDto.SettingName, userSettings[0].SettingName); - _cacheRepositoryMock.Verify( - x => x.Save($"{userId}-settings", It.IsAny>(), 2592000), + _cacheManagerMock.Verify( + x => x.SaveInCache($"{userId}-settings", It.IsAny>(), CacheType.InMemory, 2592000), Times.Once); } From e7d8bb323693c5feef3cad372f61e15eae4e8412 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:48:21 +0100 Subject: [PATCH 04/10] feat(cache): demonstrate user name caching --- ...multiple-infrastructure-implementations.md | 2 + .../BusinessServiceRegistration.cs | 1 + .../Implementations/UserNameManager.cs | 36 +++++++++++++ .../Interfaces/IUserNameManager.cs | 6 +++ .../UserNameManagerTests.cs | 54 +++++++++++++++++++ 5 files changed, 99 insertions(+) create mode 100644 src/ModularNet.Business/Implementations/UserNameManager.cs create mode 100644 src/ModularNet.Business/Interfaces/IUserNameManager.cs create mode 100644 src/ModularNet.UnitTests/UserNameManagerTests.cs diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md index 8d941e0..585abb2 100644 --- a/docs/multiple-infrastructure-implementations.md +++ b/docs/multiple-infrastructure-implementations.md @@ -23,3 +23,5 @@ Interfaces currently live in Infrastructure under the project's coding standards ## Disabled cache behavior `AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. + +`UserNameManager.GetUserFirstNameById` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `UserNameCacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersManager` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. diff --git a/src/ModularNet.Business/BusinessServiceRegistration.cs b/src/ModularNet.Business/BusinessServiceRegistration.cs index 6cc32d5..90ba46a 100644 --- a/src/ModularNet.Business/BusinessServiceRegistration.cs +++ b/src/ModularNet.Business/BusinessServiceRegistration.cs @@ -24,6 +24,7 @@ public static IServiceCollection AddBusinessServices(this IServiceCollection ser services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/ModularNet.Business/Implementations/UserNameManager.cs b/src/ModularNet.Business/Implementations/UserNameManager.cs new file mode 100644 index 0000000..bd41767 --- /dev/null +++ b/src/ModularNet.Business/Implementations/UserNameManager.cs @@ -0,0 +1,36 @@ +using Microsoft.Extensions.Logging; +using ModularNet.Business.Interfaces; +using ModularNet.Domain.Enums; + +namespace ModularNet.Business.Implementations; + +public class UserNameManager : IUserNameManager +{ + // Change this key to CacheType.Redis to select Redis for this manager. + private const CacheType UserNameCacheType = CacheType.InMemory; + private const int CacheExpirationSeconds = 300; + private readonly IUsersManager _usersManager; + private readonly ICacheManager _cacheManager; + private readonly ILogger _logger; + + public UserNameManager(IUsersManager usersManager, ICacheManager cacheManager, ILogger logger) + { + _usersManager = usersManager; + _cacheManager = cacheManager; + _logger = logger; + } + + public async Task GetUserFirstNameById(Guid userId) + { + _logger.LogDebug("Start method {Method}", nameof(GetUserFirstNameById)); + var cacheKey = $"user:{userId}:first-name"; + var firstName = await _cacheManager.GetFromCache(cacheKey, UserNameCacheType); + if (firstName != null) return firstName; + + var user = await _usersManager.GetUserById(userId); + if (user == null) return null; + + await _cacheManager.SaveInCache(cacheKey, user.FirstName, UserNameCacheType, CacheExpirationSeconds); + return user.FirstName; + } +} diff --git a/src/ModularNet.Business/Interfaces/IUserNameManager.cs b/src/ModularNet.Business/Interfaces/IUserNameManager.cs new file mode 100644 index 0000000..aa04685 --- /dev/null +++ b/src/ModularNet.Business/Interfaces/IUserNameManager.cs @@ -0,0 +1,6 @@ +namespace ModularNet.Business.Interfaces; + +public interface IUserNameManager +{ + Task GetUserFirstNameById(Guid userId); +} diff --git a/src/ModularNet.UnitTests/UserNameManagerTests.cs b/src/ModularNet.UnitTests/UserNameManagerTests.cs new file mode 100644 index 0000000..a4fdb1a --- /dev/null +++ b/src/ModularNet.UnitTests/UserNameManagerTests.cs @@ -0,0 +1,54 @@ +using Microsoft.Extensions.Logging; +using ModularNet.Business.Implementations; +using ModularNet.Business.Interfaces; +using ModularNet.Domain.Enums; +using ModularNet.UnitTests.Helpers; +using Moq; + +namespace ModularNet.UnitTests; + +public class UserNameManagerTests +{ + [Fact] + public async Task GetUserFirstNameByIdReturnsCachedName() + { + var userId = Guid.NewGuid(); + var usersManagerMock = new Mock(); + var cacheManagerMock = new Mock(); + cacheManagerMock.Setup(manager => manager.GetFromCache($"user:{userId}:first-name", CacheType.InMemory)) + .ReturnsAsync("Ada"); + var userNameManager = new UserNameManager(usersManagerMock.Object, cacheManagerMock.Object, + Mock.Of>()); + + Assert.Equal("Ada", await userNameManager.GetUserFirstNameById(userId)); + usersManagerMock.Verify(manager => manager.GetUserById(It.IsAny()), Times.Never); + } + + [Fact] + public async Task GetUserFirstNameByIdLoadsAndCachesNameOnMiss() + { + var userId = Guid.NewGuid(); + var user = UsersHelper.GetUser(); + user.FirstName = "Ada"; + var usersManagerMock = new Mock(); + usersManagerMock.Setup(manager => manager.GetUserById(userId)).ReturnsAsync(user); + var cacheManagerMock = new Mock(); + var userNameManager = new UserNameManager(usersManagerMock.Object, cacheManagerMock.Object, + Mock.Of>()); + + Assert.Equal("Ada", await userNameManager.GetUserFirstNameById(userId)); + cacheManagerMock.Verify(manager => manager.SaveInCache($"user:{userId}:first-name", "Ada", CacheType.InMemory, 300), Times.Once); + } + + [Fact] + public async Task GetUserFirstNameByIdReturnsNullWhenUserMissing() + { + var usersManagerMock = new Mock(); + var cacheManagerMock = new Mock(); + var userNameManager = new UserNameManager(usersManagerMock.Object, cacheManagerMock.Object, + Mock.Of>()); + + Assert.Null(await userNameManager.GetUserFirstNameById(Guid.NewGuid())); + cacheManagerMock.Verify(manager => manager.SaveInCache(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } +} From 2085f56512693f8d6f820c840064bbc49a3e5f59 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:49:37 +0100 Subject: [PATCH 05/10] fix(cache): put example in users manager --- ...multiple-infrastructure-implementations.md | 2 +- .../BusinessServiceRegistration.cs | 1 - .../Implementations/UserNameManager.cs | 36 ------------- .../Implementations/UsersManager.cs | 20 ++++++- .../Interfaces/IUserNameManager.cs | 6 --- .../Interfaces/IUsersManager.cs | 1 + .../UserNameManagerTests.cs | 54 ------------------- src/ModularNet.UnitTests/UsersManagerTests.cs | 39 +++++++++++++- 8 files changed, 59 insertions(+), 100 deletions(-) delete mode 100644 src/ModularNet.Business/Implementations/UserNameManager.cs delete mode 100644 src/ModularNet.Business/Interfaces/IUserNameManager.cs delete mode 100644 src/ModularNet.UnitTests/UserNameManagerTests.cs diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md index 585abb2..1eb7ddf 100644 --- a/docs/multiple-infrastructure-implementations.md +++ b/docs/multiple-infrastructure-implementations.md @@ -24,4 +24,4 @@ Interfaces currently live in Infrastructure under the project's coding standards `AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. -`UserNameManager.GetUserFirstNameById` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `UserNameCacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersManager` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. +`UsersManager.GetUserFirstNameById` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `UserNameCacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. diff --git a/src/ModularNet.Business/BusinessServiceRegistration.cs b/src/ModularNet.Business/BusinessServiceRegistration.cs index 90ba46a..6cc32d5 100644 --- a/src/ModularNet.Business/BusinessServiceRegistration.cs +++ b/src/ModularNet.Business/BusinessServiceRegistration.cs @@ -24,7 +24,6 @@ public static IServiceCollection AddBusinessServices(this IServiceCollection ser services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/ModularNet.Business/Implementations/UserNameManager.cs b/src/ModularNet.Business/Implementations/UserNameManager.cs deleted file mode 100644 index bd41767..0000000 --- a/src/ModularNet.Business/Implementations/UserNameManager.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.Extensions.Logging; -using ModularNet.Business.Interfaces; -using ModularNet.Domain.Enums; - -namespace ModularNet.Business.Implementations; - -public class UserNameManager : IUserNameManager -{ - // Change this key to CacheType.Redis to select Redis for this manager. - private const CacheType UserNameCacheType = CacheType.InMemory; - private const int CacheExpirationSeconds = 300; - private readonly IUsersManager _usersManager; - private readonly ICacheManager _cacheManager; - private readonly ILogger _logger; - - public UserNameManager(IUsersManager usersManager, ICacheManager cacheManager, ILogger logger) - { - _usersManager = usersManager; - _cacheManager = cacheManager; - _logger = logger; - } - - public async Task GetUserFirstNameById(Guid userId) - { - _logger.LogDebug("Start method {Method}", nameof(GetUserFirstNameById)); - var cacheKey = $"user:{userId}:first-name"; - var firstName = await _cacheManager.GetFromCache(cacheKey, UserNameCacheType); - if (firstName != null) return firstName; - - var user = await _usersManager.GetUserById(userId); - if (user == null) return null; - - await _cacheManager.SaveInCache(cacheKey, user.FirstName, UserNameCacheType, CacheExpirationSeconds); - return user.FirstName; - } -} diff --git a/src/ModularNet.Business/Implementations/UsersManager.cs b/src/ModularNet.Business/Implementations/UsersManager.cs index 5f164de..ebc4adf 100644 --- a/src/ModularNet.Business/Implementations/UsersManager.cs +++ b/src/ModularNet.Business/Implementations/UsersManager.cs @@ -9,6 +9,9 @@ namespace ModularNet.Business.Implementations; public class UsersManager : IUsersManager { + private const CacheType UserNameCacheType = CacheType.InMemory; + private const int UserNameCacheExpirationSeconds = 300; + private readonly ICacheManager _cacheManager; private readonly IAppSettingsManager _appSettingsManager; private readonly IAuditsManager _auditsManager; private readonly IAuthenticationService _authenticationService; @@ -21,7 +24,7 @@ public class UsersManager : IUsersManager public UsersManager(IUsersRepository usersRepository, ILogger logger, IEncryptManager encryptManager, IEmailServiceManager emailServiceManager, IAuditsManager auditsManager, IAuthenticationService authenticationService, IAppSettingsManager appSettingsManager, - IUnitOfWork unitOfWork) + IUnitOfWork unitOfWork, ICacheManager cacheManager) { _usersRepository = usersRepository; _logger = logger; @@ -31,6 +34,7 @@ public UsersManager(IUsersRepository usersRepository, ILogger logg _authenticationService = authenticationService; _appSettingsManager = appSettingsManager; _unitOfWork = unitOfWork; + _cacheManager = cacheManager; _logger.LogDebug($"{nameof(UsersManager)} constructed"); } @@ -127,6 +131,20 @@ await _usersRepository.UpdateUserLoginDate(userSignInRequest.Id, return await _usersRepository.GetUserById(userId); } + public async Task GetUserFirstNameById(Guid userId) + { + _logger.LogDebug("Start method {Method}", nameof(GetUserFirstNameById)); + var cacheKey = $"user:{userId}:first-name"; + var firstName = await _cacheManager.GetFromCache(cacheKey, UserNameCacheType); + if (firstName != null) return firstName; + + var user = await _usersRepository.GetUserById(userId); + if (user == null) return null; + + await _cacheManager.SaveInCache(cacheKey, user.FirstName, UserNameCacheType, UserNameCacheExpirationSeconds); + return user.FirstName; + } + public async Task SetUserEmailAsVerified(Guid userId) { await _usersRepository.SetUserEmailAsVerified(userId); diff --git a/src/ModularNet.Business/Interfaces/IUserNameManager.cs b/src/ModularNet.Business/Interfaces/IUserNameManager.cs deleted file mode 100644 index aa04685..0000000 --- a/src/ModularNet.Business/Interfaces/IUserNameManager.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace ModularNet.Business.Interfaces; - -public interface IUserNameManager -{ - Task GetUserFirstNameById(Guid userId); -} diff --git a/src/ModularNet.Business/Interfaces/IUsersManager.cs b/src/ModularNet.Business/Interfaces/IUsersManager.cs index c8b1fe0..19df529 100644 --- a/src/ModularNet.Business/Interfaces/IUsersManager.cs +++ b/src/ModularNet.Business/Interfaces/IUsersManager.cs @@ -9,6 +9,7 @@ public interface IUsersManager Task LoginUser(UserSignInRequest userSignInRequest); Task GetUserByEmail(string email); Task GetUserById(Guid userId); + Task GetUserFirstNameById(Guid userId); Task SetUserEmailAsVerified(Guid userId); Task SetTermsAndConditionsAsAccepted(Guid userId); Task DeactivateAccount(Guid userId); diff --git a/src/ModularNet.UnitTests/UserNameManagerTests.cs b/src/ModularNet.UnitTests/UserNameManagerTests.cs deleted file mode 100644 index a4fdb1a..0000000 --- a/src/ModularNet.UnitTests/UserNameManagerTests.cs +++ /dev/null @@ -1,54 +0,0 @@ -using Microsoft.Extensions.Logging; -using ModularNet.Business.Implementations; -using ModularNet.Business.Interfaces; -using ModularNet.Domain.Enums; -using ModularNet.UnitTests.Helpers; -using Moq; - -namespace ModularNet.UnitTests; - -public class UserNameManagerTests -{ - [Fact] - public async Task GetUserFirstNameByIdReturnsCachedName() - { - var userId = Guid.NewGuid(); - var usersManagerMock = new Mock(); - var cacheManagerMock = new Mock(); - cacheManagerMock.Setup(manager => manager.GetFromCache($"user:{userId}:first-name", CacheType.InMemory)) - .ReturnsAsync("Ada"); - var userNameManager = new UserNameManager(usersManagerMock.Object, cacheManagerMock.Object, - Mock.Of>()); - - Assert.Equal("Ada", await userNameManager.GetUserFirstNameById(userId)); - usersManagerMock.Verify(manager => manager.GetUserById(It.IsAny()), Times.Never); - } - - [Fact] - public async Task GetUserFirstNameByIdLoadsAndCachesNameOnMiss() - { - var userId = Guid.NewGuid(); - var user = UsersHelper.GetUser(); - user.FirstName = "Ada"; - var usersManagerMock = new Mock(); - usersManagerMock.Setup(manager => manager.GetUserById(userId)).ReturnsAsync(user); - var cacheManagerMock = new Mock(); - var userNameManager = new UserNameManager(usersManagerMock.Object, cacheManagerMock.Object, - Mock.Of>()); - - Assert.Equal("Ada", await userNameManager.GetUserFirstNameById(userId)); - cacheManagerMock.Verify(manager => manager.SaveInCache($"user:{userId}:first-name", "Ada", CacheType.InMemory, 300), Times.Once); - } - - [Fact] - public async Task GetUserFirstNameByIdReturnsNullWhenUserMissing() - { - var usersManagerMock = new Mock(); - var cacheManagerMock = new Mock(); - var userNameManager = new UserNameManager(usersManagerMock.Object, cacheManagerMock.Object, - Mock.Of>()); - - Assert.Null(await userNameManager.GetUserFirstNameById(Guid.NewGuid())); - cacheManagerMock.Verify(manager => manager.SaveInCache(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); - } -} diff --git a/src/ModularNet.UnitTests/UsersManagerTests.cs b/src/ModularNet.UnitTests/UsersManagerTests.cs index 2fb23fe..7bc2280 100644 --- a/src/ModularNet.UnitTests/UsersManagerTests.cs +++ b/src/ModularNet.UnitTests/UsersManagerTests.cs @@ -2,6 +2,7 @@ using ModularNet.Business.Implementations; using ModularNet.Business.Interfaces; using ModularNet.Domain.Entities; +using ModularNet.Domain.Enums; using ModularNet.Domain.Requests; using ModularNet.Infrastructure.Interfaces; using ModularNet.UnitTests.Helpers; @@ -11,6 +12,7 @@ namespace ModularNet.UnitTests; public class UsersManagerTests { + private readonly Mock _cacheManagerMock = new(); private readonly Mock _appSettingsManagerMock = new(); private readonly Mock _auditsManagerMock = new(); private readonly Mock _authenticationServiceMock = new(); @@ -30,7 +32,8 @@ private UsersManager CreateUsersManager() _auditsManagerMock.Object, _authenticationServiceMock.Object, _appSettingsManagerMock.Object, - _unitOfWorkMock.Object); + _unitOfWorkMock.Object, + _cacheManagerMock.Object); } [Fact] @@ -278,4 +281,38 @@ public async Task LoginUserInFirebaseLogsAndThrowsWhenExceptionOccurs() await Assert.ThrowsAsync(() => usersManager.LoginUserInFirebase(email, password)); } + [Fact] + public async Task GetUserFirstNameByIdReturnsCachedName() + { + var userId = Guid.NewGuid(); + _cacheManagerMock.Setup(manager => manager.GetFromCache($"user:{userId}:first-name", CacheType.InMemory)) + .ReturnsAsync("Ada"); + var usersManager = CreateUsersManager(); + + Assert.Equal("Ada", await usersManager.GetUserFirstNameById(userId)); + _usersRepositoryMock.Verify(repository => repository.GetUserById(It.IsAny()), Times.Never); + } + + [Fact] + public async Task GetUserFirstNameByIdLoadsAndCachesNameOnMiss() + { + var userId = Guid.NewGuid(); + var user = UsersHelper.GetUser(); + user.FirstName = "Ada"; + _usersRepositoryMock.Setup(repository => repository.GetUserById(userId)).ReturnsAsync(user); + var usersManager = CreateUsersManager(); + + Assert.Equal("Ada", await usersManager.GetUserFirstNameById(userId)); + _cacheManagerMock.Verify(manager => manager.SaveInCache($"user:{userId}:first-name", "Ada", CacheType.InMemory, 300), Times.Once); + } + + [Fact] + public async Task GetUserFirstNameByIdReturnsNullWhenUserMissing() + { + var usersManager = CreateUsersManager(); + + Assert.Null(await usersManager.GetUserFirstNameById(Guid.NewGuid())); + _cacheManagerMock.Verify(manager => manager.SaveInCache(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + } From a4ad22e4f8ef6f926213182305e19f806d6527c0 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:50:20 +0100 Subject: [PATCH 06/10] fix(users): clarify first name lookup name --- docs/multiple-infrastructure-implementations.md | 2 +- .../Implementations/UsersManager.cs | 4 ++-- src/ModularNet.Business/Interfaces/IUsersManager.cs | 2 +- src/ModularNet.UnitTests/UsersManagerTests.cs | 12 ++++++------ 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md index 1eb7ddf..859f18e 100644 --- a/docs/multiple-infrastructure-implementations.md +++ b/docs/multiple-infrastructure-implementations.md @@ -24,4 +24,4 @@ Interfaces currently live in Infrastructure under the project's coding standards `AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. -`UsersManager.GetUserFirstNameById` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `UserNameCacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. +`UsersManager.GetUserFirstNameByUserId` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `UserNameCacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. diff --git a/src/ModularNet.Business/Implementations/UsersManager.cs b/src/ModularNet.Business/Implementations/UsersManager.cs index ebc4adf..d37cff7 100644 --- a/src/ModularNet.Business/Implementations/UsersManager.cs +++ b/src/ModularNet.Business/Implementations/UsersManager.cs @@ -131,9 +131,9 @@ await _usersRepository.UpdateUserLoginDate(userSignInRequest.Id, return await _usersRepository.GetUserById(userId); } - public async Task GetUserFirstNameById(Guid userId) + public async Task GetUserFirstNameByUserId(Guid userId) { - _logger.LogDebug("Start method {Method}", nameof(GetUserFirstNameById)); + _logger.LogDebug("Start method {Method}", nameof(GetUserFirstNameByUserId)); var cacheKey = $"user:{userId}:first-name"; var firstName = await _cacheManager.GetFromCache(cacheKey, UserNameCacheType); if (firstName != null) return firstName; diff --git a/src/ModularNet.Business/Interfaces/IUsersManager.cs b/src/ModularNet.Business/Interfaces/IUsersManager.cs index 19df529..93998cc 100644 --- a/src/ModularNet.Business/Interfaces/IUsersManager.cs +++ b/src/ModularNet.Business/Interfaces/IUsersManager.cs @@ -9,7 +9,7 @@ public interface IUsersManager Task LoginUser(UserSignInRequest userSignInRequest); Task GetUserByEmail(string email); Task GetUserById(Guid userId); - Task GetUserFirstNameById(Guid userId); + Task GetUserFirstNameByUserId(Guid userId); Task SetUserEmailAsVerified(Guid userId); Task SetTermsAndConditionsAsAccepted(Guid userId); Task DeactivateAccount(Guid userId); diff --git a/src/ModularNet.UnitTests/UsersManagerTests.cs b/src/ModularNet.UnitTests/UsersManagerTests.cs index 7bc2280..3f7e218 100644 --- a/src/ModularNet.UnitTests/UsersManagerTests.cs +++ b/src/ModularNet.UnitTests/UsersManagerTests.cs @@ -282,19 +282,19 @@ await Assert.ThrowsAsync(() => usersManager.LoginUserInFirebase(email, password)); } [Fact] - public async Task GetUserFirstNameByIdReturnsCachedName() + public async Task GetUserFirstNameByUserIdReturnsCachedName() { var userId = Guid.NewGuid(); _cacheManagerMock.Setup(manager => manager.GetFromCache($"user:{userId}:first-name", CacheType.InMemory)) .ReturnsAsync("Ada"); var usersManager = CreateUsersManager(); - Assert.Equal("Ada", await usersManager.GetUserFirstNameById(userId)); + Assert.Equal("Ada", await usersManager.GetUserFirstNameByUserId(userId)); _usersRepositoryMock.Verify(repository => repository.GetUserById(It.IsAny()), Times.Never); } [Fact] - public async Task GetUserFirstNameByIdLoadsAndCachesNameOnMiss() + public async Task GetUserFirstNameByUserIdLoadsAndCachesNameOnMiss() { var userId = Guid.NewGuid(); var user = UsersHelper.GetUser(); @@ -302,16 +302,16 @@ public async Task GetUserFirstNameByIdLoadsAndCachesNameOnMiss() _usersRepositoryMock.Setup(repository => repository.GetUserById(userId)).ReturnsAsync(user); var usersManager = CreateUsersManager(); - Assert.Equal("Ada", await usersManager.GetUserFirstNameById(userId)); + Assert.Equal("Ada", await usersManager.GetUserFirstNameByUserId(userId)); _cacheManagerMock.Verify(manager => manager.SaveInCache($"user:{userId}:first-name", "Ada", CacheType.InMemory, 300), Times.Once); } [Fact] - public async Task GetUserFirstNameByIdReturnsNullWhenUserMissing() + public async Task GetUserFirstNameByUserIdReturnsNullWhenUserMissing() { var usersManager = CreateUsersManager(); - Assert.Null(await usersManager.GetUserFirstNameById(Guid.NewGuid())); + Assert.Null(await usersManager.GetUserFirstNameByUserId(Guid.NewGuid())); _cacheManagerMock.Verify(manager => manager.SaveInCache(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } From c91ac321b9bb780db1d9f19afa7b542371527926 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:52:35 +0100 Subject: [PATCH 07/10] refactor(users): generalize cache type name --- docs/multiple-infrastructure-implementations.md | 2 +- src/ModularNet.Business/Implementations/UsersManager.cs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md index 859f18e..7960f97 100644 --- a/docs/multiple-infrastructure-implementations.md +++ b/docs/multiple-infrastructure-implementations.md @@ -24,4 +24,4 @@ Interfaces currently live in Infrastructure under the project's coding standards `AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. -`UsersManager.GetUserFirstNameByUserId` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `UserNameCacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. +`UsersManager.GetUserFirstNameByUserId` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `CacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. diff --git a/src/ModularNet.Business/Implementations/UsersManager.cs b/src/ModularNet.Business/Implementations/UsersManager.cs index d37cff7..a664a06 100644 --- a/src/ModularNet.Business/Implementations/UsersManager.cs +++ b/src/ModularNet.Business/Implementations/UsersManager.cs @@ -9,7 +9,7 @@ namespace ModularNet.Business.Implementations; public class UsersManager : IUsersManager { - private const CacheType UserNameCacheType = CacheType.InMemory; + private const CacheType CacheType = ModularNet.Domain.Enums.CacheType.InMemory; private const int UserNameCacheExpirationSeconds = 300; private readonly ICacheManager _cacheManager; private readonly IAppSettingsManager _appSettingsManager; @@ -135,13 +135,13 @@ await _usersRepository.UpdateUserLoginDate(userSignInRequest.Id, { _logger.LogDebug("Start method {Method}", nameof(GetUserFirstNameByUserId)); var cacheKey = $"user:{userId}:first-name"; - var firstName = await _cacheManager.GetFromCache(cacheKey, UserNameCacheType); + var firstName = await _cacheManager.GetFromCache(cacheKey, CacheType); if (firstName != null) return firstName; var user = await _usersRepository.GetUserById(userId); if (user == null) return null; - await _cacheManager.SaveInCache(cacheKey, user.FirstName, UserNameCacheType, UserNameCacheExpirationSeconds); + await _cacheManager.SaveInCache(cacheKey, user.FirstName, CacheType, UserNameCacheExpirationSeconds); return user.FirstName; } From 5f73dcc26d72b7fbd9202ec720aea237c63544c5 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:54:59 +0100 Subject: [PATCH 08/10] docs: move provider guidance to readme --- README.md | 28 ++++++++++++++++++- ...multiple-infrastructure-implementations.md | 27 ------------------ 2 files changed, 27 insertions(+), 28 deletions(-) delete mode 100644 docs/multiple-infrastructure-implementations.md diff --git a/README.md b/README.md index 01bc12c..0fdb80c 100644 --- a/README.md +++ b/README.md @@ -41,4 +41,30 @@ All architectural rules, layer responsibilities, differences from Onion Architec - **[Wiki](https://github.com/ale206/ModularNet/wiki):** Component-by-component reference for the solution. - **[Discussions](https://github.com/ale206/ModularNet/discussions):** Ideas, questions, and feedback. Contributions and Pull Requests are welcome! -For an example of selecting one or multiple infrastructure implementations, see [Multiple infrastructure implementations](docs/multiple-infrastructure-implementations.md). +## Multiple infrastructure implementations + +The cache registrations demonstrate one contract, `ICacheRepository`, backed by the existing in-memory and Redis repositories. `AddInfrastructureServices` registers each adapter with a `CacheType` key. Both can be used in the same scope; Redis still requires its normal connection configuration. + +`CacheManager` injects both keyed adapters and selects one using `CacheType`. Other managers use `ICacheManager`, as in `UsersSettingsManager`. To inject a known backend into its corresponding manager: + +```csharp +public CacheManager( + [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository) +{ + _cacheRepository = cacheRepository; +} +``` + +Import `Microsoft.Extensions.DependencyInjection`, `ModularNet.Domain.Enums`, and `ModularNet.Infrastructure.Interfaces`. Use `CacheType.Redis` for Redis. The current `CacheManager` injects both keys, so removing a registration requires updating its constructor and selection logic. A manager designed for a single backend can inject just that keyed implementation. For runtime selection, resolve the requested key within the current DI scope with `GetRequiredKeyedService(cacheType)`. An unknown or unregistered key fails rather than silently selecting another backend. Avoid resolving scoped services from the root provider. + +To add a backend, implement the contract, register it with a distinct key and appropriate lifetime, and test all contract operations. Do not register multiple unkeyed implementations expecting ordinary injection to select between them: .NET resolves the last registration for a single service; `IEnumerable` returns all unkeyed registrations. + +The adapters preserve the existing cache API and lifetimes. They are an example of selection, not database provider implementations. To add PostgreSQL or another database, implement provider-specific repositories and SQL, connection factory, and transaction handling; select a consistent set together. The current MySQL repositories contain provider-specific SQL. Repositories participating in one unit of work must share the same scoped connection and transaction; keyed registration alone does not make cross-provider transactions atomic. Test each provider against its actual database, including commit and rollback. + +Interfaces currently live in Infrastructure under the project's coding standards. Multiple implementations can coexist there in provider-specific folders. If provider dependencies or independent deployment justify separate projects, first move shared contracts to an Infrastructure abstractions project, then have Business and each provider project reference it; keep registration in the application composition root. This adds project and migration overhead, so the template keeps its existing layout until that separation is needed. + +### Disabled cache behavior + +`AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. + +`UsersManager.GetUserFirstNameByUserId` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `CacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. diff --git a/docs/multiple-infrastructure-implementations.md b/docs/multiple-infrastructure-implementations.md deleted file mode 100644 index 7960f97..0000000 --- a/docs/multiple-infrastructure-implementations.md +++ /dev/null @@ -1,27 +0,0 @@ -# Multiple infrastructure implementations - -The cache registrations demonstrate one contract, `ICacheRepository`, backed by the existing in-memory and Redis repositories. `AddInfrastructureServices` registers each adapter with a `CacheType` key. Both can be used in the same scope; Redis still requires its normal connection configuration. - -`CacheManager` injects both keyed adapters and selects one using `CacheType`. Other managers use `ICacheManager`, as in `UsersSettingsManager`. To inject a known backend into its corresponding manager: - -```csharp -public CacheManager( - [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository) -{ - _cacheRepository = cacheRepository; -} -``` - -Import `Microsoft.Extensions.DependencyInjection`, `ModularNet.Domain.Enums`, and `ModularNet.Infrastructure.Interfaces`. Use `CacheType.Redis` for Redis. For a single backend, register only that implementation, and inject it with its key; alternatively register it unkeyed and inject `ICacheRepository` normally. For runtime selection, resolve the requested key within the current DI scope with `GetRequiredKeyedService(cacheType)`. An unknown or unregistered key fails rather than silently selecting another backend. Avoid resolving scoped services from the root provider. - -To add a backend, implement the contract, register it with a distinct key and appropriate lifetime, and test all contract operations. Do not register multiple unkeyed implementations expecting ordinary injection to select between them: .NET resolves the last registration for a single service; `IEnumerable` returns all unkeyed registrations. - -The adapters preserve the existing cache API and lifetimes. They are an example of selection, not database provider implementations. To add PostgreSQL or another database, implement provider-specific repositories and SQL, connection factory, and transaction handling; select a consistent set together. The current MySQL repositories contain provider-specific SQL. Repositories participating in one unit of work must share the same scoped connection and transaction; keyed registration alone does not make cross-provider transactions atomic. Test each provider against its actual database, including commit and rollback. - -Interfaces currently live in Infrastructure under the project's coding standards. Multiple implementations can coexist there in provider-specific folders. If provider dependencies or independent deployment justify separate projects, first move shared contracts to an Infrastructure abstractions project, then have Business and each provider project reference it; keep registration in the application composition root. This adds project and migration overhead, so the template keeps its existing layout until that separation is needed. - -## Disabled cache behavior - -`AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. - -`UsersManager.GetUserFirstNameByUserId` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `CacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. From 6634eef4c0cf0c5a34fd24c55d18d938fd582dda Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:55:44 +0100 Subject: [PATCH 09/10] docs: shorten infrastructure guidance --- README.md | 26 ++++---------------------- 1 file changed, 4 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 0fdb80c..44e4b84 100644 --- a/README.md +++ b/README.md @@ -43,28 +43,10 @@ All architectural rules, layer responsibilities, differences from Onion Architec ## Multiple infrastructure implementations -The cache registrations demonstrate one contract, `ICacheRepository`, backed by the existing in-memory and Redis repositories. `AddInfrastructureServices` registers each adapter with a `CacheType` key. Both can be used in the same scope; Redis still requires its normal connection configuration. +`CacheManager` uses keyed `ICacheRepository` adapters for memory and Redis. Managers select a backend through `ICacheManager`; for example, change the `CacheType` constant in `UsersManager` to `CacheType.Redis`. To add a backend, implement and register the adapter with a new key and update `CacheManager`. -`CacheManager` injects both keyed adapters and selects one using `CacheType`. Other managers use `ICacheManager`, as in `UsersSettingsManager`. To inject a known backend into its corresponding manager: +`MemoryCacheEnabled` and `RedisCacheEnabled` control cache operations, not registration. A disabled cache returns misses and ignores writes and removals; it does not fall back to another cache. Redis requires its connection configuration when enabled. For value types, a miss returns `default` and cannot be distinguished from a cached default value. -```csharp -public CacheManager( - [FromKeyedServices(CacheType.InMemory)] ICacheRepository cacheRepository) -{ - _cacheRepository = cacheRepository; -} -``` +`UsersManager.GetUserFirstNameByUserId` demonstrates caching for five minutes. Invalidate the key when names change, or choose an acceptable expiration. -Import `Microsoft.Extensions.DependencyInjection`, `ModularNet.Domain.Enums`, and `ModularNet.Infrastructure.Interfaces`. Use `CacheType.Redis` for Redis. The current `CacheManager` injects both keys, so removing a registration requires updating its constructor and selection logic. A manager designed for a single backend can inject just that keyed implementation. For runtime selection, resolve the requested key within the current DI scope with `GetRequiredKeyedService(cacheType)`. An unknown or unregistered key fails rather than silently selecting another backend. Avoid resolving scoped services from the root provider. - -To add a backend, implement the contract, register it with a distinct key and appropriate lifetime, and test all contract operations. Do not register multiple unkeyed implementations expecting ordinary injection to select between them: .NET resolves the last registration for a single service; `IEnumerable` returns all unkeyed registrations. - -The adapters preserve the existing cache API and lifetimes. They are an example of selection, not database provider implementations. To add PostgreSQL or another database, implement provider-specific repositories and SQL, connection factory, and transaction handling; select a consistent set together. The current MySQL repositories contain provider-specific SQL. Repositories participating in one unit of work must share the same scoped connection and transaction; keyed registration alone does not make cross-provider transactions atomic. Test each provider against its actual database, including commit and rollback. - -Interfaces currently live in Infrastructure under the project's coding standards. Multiple implementations can coexist there in provider-specific folders. If provider dependencies or independent deployment justify separate projects, first move shared contracts to an Infrastructure abstractions project, then have Business and each provider project reference it; keep registration in the application composition root. This adds project and migration overhead, so the template keeps its existing layout until that separation is needed. - -### Disabled cache behavior - -`AppSettings:ModularNetConfig:RedisCacheEnabled` and `MemoryCacheEnabled` control the underlying repositories, not DI registrations. When the selected cache is disabled, reads return `default` (a cache miss for reference types), and writes and removals do nothing. Redis is not contacted and there is no automatic fallback to memory. `UsersSettingsManager` handles a cache miss through `ICacheManager` by reading the database. This also means disabled caching increases database traffic. Enable Redis and configure its connection before selecting it if caching is required. For value types, `default` cannot distinguish a cache miss from a cached default value. - -`UsersManager.GetUserFirstNameByUserId` shows a consumer choosing `CacheType.InMemory` through `ICacheManager`. Change its `CacheType` constant to `CacheType.Redis` to use Redis. On a miss it loads the user through `IUsersRepository` and caches the first name for five minutes. If names can change, invalidate the same key on update or choose an acceptable expiration; disabled caching always reads the user. +Database providers also need provider-specific SQL, connection factories, and transaction handling. Repositories in one unit of work must share a scoped connection and transaction. Test each provider against its database; keyed registration alone does not provide cross-provider transactions. From 45ca594f76625a467c14094c15f0a8690b9f1c76 Mon Sep 17 00:00:00 2001 From: Alessio Di Salvo Date: Wed, 4 Nov 2026 15:56:31 +0100 Subject: [PATCH 10/10] docs: generalize implementation guidance --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 44e4b84..fbb2a3a 100644 --- a/README.md +++ b/README.md @@ -43,10 +43,10 @@ All architectural rules, layer responsibilities, differences from Onion Architec ## Multiple infrastructure implementations -`CacheManager` uses keyed `ICacheRepository` adapters for memory and Redis. Managers select a backend through `ICacheManager`; for example, change the `CacheType` constant in `UsersManager` to `CacheType.Redis`. To add a backend, implement and register the adapter with a new key and update `CacheManager`. +Define a shared Infrastructure interface for interchangeable implementations, register each with a distinct dependency-injection key, and select the implementation in its corresponding manager. Other managers access it through that manager's interface. Add a new implementation by registering a new key and updating the manager's selection logic. -`MemoryCacheEnabled` and `RedisCacheEnabled` control cache operations, not registration. A disabled cache returns misses and ignores writes and removals; it does not fall back to another cache. Redis requires its connection configuration when enabled. For value types, a miss returns `default` and cannot be distinguished from a cached default value. +For example, `CacheManager` selects keyed `ICacheRepository` adapters for memory or Redis. `UsersManager` chooses a backend through `ICacheManager` using its `CacheType` constant; `GetUserFirstNameByUserId` caches a name for five minutes. Invalidate the key when names change, or choose an acceptable expiration. -`UsersManager.GetUserFirstNameByUserId` demonstrates caching for five minutes. Invalidate the key when names change, or choose an acceptable expiration. +`MemoryCacheEnabled` and `RedisCacheEnabled` control operations, not registrations. A disabled cache returns misses and ignores writes and removals; it does not fall back. Redis needs its connection configuration when enabled. For value types, a miss returns `default`, indistinguishable from a cached default value. -Database providers also need provider-specific SQL, connection factories, and transaction handling. Repositories in one unit of work must share a scoped connection and transaction. Test each provider against its database; keyed registration alone does not provide cross-provider transactions. +Database implementations also need provider-specific SQL, connections, and transaction handling. Repositories in one unit of work must share a scoped connection and transaction. Test each provider against its database; keyed registration alone does not provide cross-provider transactions.