/// <summary> /// Create a basic repository with hub. /// </summary> /// <returns></returns> public async Task <RepositoryManager> CreateRepositoryWithHub() { var context = await CreateRepositoryEmpty(); var userStore = new UserStore <ApplicationUser>(context); var userManager = MockHelpers.TestUserManager(userStore); // instance of the memory cache. var memoryCache = new MemoryDistributedCache(new OptionsWrapper <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions())); var cacheService = new CacheService(memoryCache); var database = new RepositoryManager(context, userManager, cacheService, _loggerFactory, null); var hub = new DexihHub() { Name = "test", Description = "hub description", EncryptionKey = "123" }; var user = await database.FindByEmailAsync("*****@*****.**"); var newHub = await database.SaveHub(hub, user, CancellationToken.None); Assert.Equal(1, context.DexihHubs.Count()); return(database); }
public void Constructor_Settings_Null() { var memoryCache = new MemoryCache(new MemoryCacheOptions()); var distributedCache = new MemoryDistributedCache(memoryCache); new AddressRegistry(null, distributedCache); }
public void Constructor_AddressRegistry_Null() { var memoryCache = new MemoryCache(new MemoryCacheOptions()); var distributedCache = new MemoryDistributedCache(memoryCache); new CollaborationProtocolRegistry(new CollaborationProtocolRegistrySettings(), distributedCache, null); }
public async Task GetOrCreateStringAsync_MemoryEmpty_RedisContains_CallTwice() { const string generatedKey = "key1"; IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); var options = Options.Create(new MemoryDistributedCacheOptions()); var redisCache = new MemoryDistributedCache(options); await redisCache.SetStringAsync(generatedKey, Test); var logger = Substitute.For <LoggerMock <CommonCachingService> >(); var cacheService = new CommonCachingService(memoryCache, redisCache, logger); var result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5)); Assert.AreEqual(Test, result); result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5)); Assert.AreEqual(Test, result); logger.Received(1).Log(LogLevel.Debug, $"Getting cached value from Distributed cache for key {generatedKey}"); logger.Received(1).Log(LogLevel.Debug, $"Read cached value from Distributed cache for key {generatedKey}"); logger.Received(0).Log(LogLevel.Debug, $"Stored in Distributed cache for key {generatedKey}"); }
public void GivenCustomerWhenSaveCustomerThenSaveToDatabase() { // Arrange var cacheOption = Options.Create(new MemoryDistributedCacheOptions()); var cache = new MemoryDistributedCache(cacheOption); var options = new DbContextOptionsBuilder <CustomerDbContext>() .UseInMemoryDatabase(databaseName: "customerdatabse") .Options; var expect = new Customer { Age = 35, City = "Chennai", Country = "India", Name = "Mark", State = "Tamil Nadu", CustomerId = Guid.NewGuid(), }; var customerDbContext = new CustomerDbContext(options); var customerRedisContext = new CustomerRedisContext(cache, customerDbContext); // Act var response = customerRedisContext.SetCustomer(expect); var cachedCustomer = cache.Get <Customer>($"{expect.CustomerId}"); // Assert Assert.True(response); Assert.Equal(cachedCustomer.Country, expect.Country); }
public static RepositoryManager CreateRepositoryManager() { // create an in memory database for testing var options = new DbContextOptionsBuilder <DexihRepositoryContext>() .UseInMemoryDatabase("dexih_repository_" + Guid.NewGuid()) .Options; var repositoryContext = new DexihRepositoryContext(options); repositoryContext.Database.EnsureCreated(); // instance of the memory cache. var memoryCache = new MemoryDistributedCache(new OptionsWrapper <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions())); var cacheService = new CacheService(memoryCache); var userStore = new UserStore <ApplicationUser>(repositoryContext); var roleStore = new RoleStore <IdentityRole>(repositoryContext); var userManager = TestUserManager(userStore); var roleManager = TestRoleManager(roleStore); var seedData = new SeedData(); seedData.UpdateReferenceData(roleManager, userManager).Wait(); return(new RepositoryManager(repositoryContext, userManager, cacheService, new LoggerFactory(), null)); }
public void CanWriteCacheVaryByRules() { var cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var responseCache = new DistributedResponseCache(cache); using var stream = new MemoryStream(); using (var writer = new StreamWriter(stream, leaveOpen: true)) { writer.Write("data"); } stream.Position = 0; Assert.That(() => responseCache.Set("test", new CachedVaryByRules { Headers = new StringValues("x-test-header"), QueryKeys = new StringValues("x-test-query"), VaryByKeyPrefix = "test" }, TimeSpan.FromMinutes(1)), Throws.Nothing); var item = responseCache.Get("test"); Assert.That(item, Is.Not.Null); var realItem = item as CachedVaryByRules; Assert.That(item, Is.Not.Null); }
public async Task HandlesDistributedCacheFailuresInTheMiddleOfAnOperationAsync() { using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { var distributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var chaosDistributedCache = new ChaosDistributedCache(distributedCache); using (var fusionCache = new FusionCache(new FusionCacheOptions(), memoryCache).SetupDistributedCache(chaosDistributedCache, new FusionCacheNewtonsoftJsonSerializer())) { var task = fusionCache.GetOrSetAsync <int>("foo", async _ => { await Task.Delay(2_000); return(42); }, new FusionCacheEntryOptions(TimeSpan.FromSeconds(10))); await Task.Delay(500); chaosDistributedCache.SetAlwaysThrow(); var value = await task; chaosDistributedCache.SetNeverThrow(); // END RESULT IS WHAT EXPECTED Assert.Equal(42, value); // MEMORY CACHE HAS BEEN UPDATED Assert.Equal(42, memoryCache.Get <FusionCacheEntry <int> >("foo").Value); // DISTRIBUTED CACHE HAS -NOT- BEEN UPDATED Assert.Null(distributedCache.GetString("foo")); } } }
public async Task GetOrCreateStringAsync_MemoryEmpty_RedisContains_CallTwice() { const string generatedKey = "key1"; IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); var options = Options.Create(new MemoryDistributedCacheOptions()); var redisCache = new MemoryDistributedCache(options); await redisCache.SetStringAsync(generatedKey, Test); var logger = Substitute.For <ILogger <CommonCachingService> >(); var cacheService = new CommonCachingService(memoryCache, redisCache, logger); var result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5)); Assert.AreEqual(Test, result); result = await cacheService.GetOrCreateStringAsync(generatedKey, () => Task.FromResult(Test), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(5)); Assert.AreEqual(Test, result); logger.Received(1).Log(LogLevel.Debug, Arg.Any <EventId>(), Arg.Is <Microsoft.Extensions.Logging.Internal.FormattedLogValues>(flv => flv.ToString() == $"Getting cached value from Distributed cache for key {generatedKey}"), null, Arg.Any <Func <Object, Exception, string> >()); logger.Received(1).Log(LogLevel.Debug, Arg.Any <EventId>(), Arg.Is <Microsoft.Extensions.Logging.Internal.FormattedLogValues>(flv => flv.ToString() == $"Read cached value from Distributed cache for key {generatedKey}"), null, Arg.Any <Func <Object, Exception, string> >()); logger.Received(0).Log(LogLevel.Debug, Arg.Any <EventId>(), Arg.Is <Microsoft.Extensions.Logging.Internal.FormattedLogValues>(flv => flv.ToString() == $"Stored in Distributed cache for key {generatedKey}"), null, Arg.Any <Func <Object, Exception, string> >()); }
public async Task DistributedCacheCircuitBreakerActuallyWorksAsync(SerializerType serializerType) { var circuitBreakerDuration = TimeSpan.FromSeconds(2); var distributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var chaosDistributedCache = new ChaosDistributedCache(distributedCache); using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { using (var fusionCache = new FusionCache(new FusionCacheOptions() { DistributedCacheCircuitBreakerDuration = circuitBreakerDuration }, memoryCache)) { fusionCache.DefaultEntryOptions.AllowBackgroundDistributedCacheOperations = false; fusionCache.SetupDistributedCache(chaosDistributedCache, GetSerializer(serializerType)); await fusionCache.SetAsync <int>("foo", 1, options => options.SetDurationSec(60).SetFailSafe(true)); chaosDistributedCache.SetAlwaysThrow(); await fusionCache.SetAsync <int>("foo", 2, options => options.SetDurationSec(60).SetFailSafe(true)); chaosDistributedCache.SetNeverThrow(); await fusionCache.SetAsync <int>("foo", 3, options => options.SetDurationSec(60).SetFailSafe(true)); await Task.Delay(circuitBreakerDuration).ConfigureAwait(false); memoryCache.Remove("foo"); var res = await fusionCache.GetOrDefaultAsync <int>("foo", -1); Assert.Equal(1, res); } } }
public L1L2RedisCacheTests() { L1Cache = new MemoryCache( Options.Create(new MemoryCacheOptions())); L2Cache = new MemoryDistributedCache( Options.Create( new MemoryDistributedCacheOptions())); L1L2RedisCacheOptions = Options .Create( new L1L2RedisCacheOptions { InstanceName = "L1L2RedisCache:Test:", }) .Value; var mockDatabase = new Mock <IDatabase>(); mockDatabase .Setup( d => d.HashGetAll( It.IsAny <RedisKey>(), It.IsAny <CommandFlags>())) .Returns <RedisKey, CommandFlags>( (k, cF) => { var key = ((string)k)[
public WidgetServiceTest() { // cache and logger var serviceProvider = new ServiceCollection().AddMemoryCache().AddLogging().BuildServiceProvider(); var cache = new MemoryDistributedCache(serviceProvider.GetService <IOptions <MemoryDistributedCacheOptions> >()); var loggerTheme = serviceProvider.GetService <ILoggerFactory>().CreateLogger <ThemeService>(); var loggerWidget = serviceProvider.GetService <ILoggerFactory>().CreateLogger <WidgetService>(); // mock ContentRootPath to return current dir var hostingEnvMock = new Mock <IWebHostEnvironment>(); hostingEnvMock.Setup(env => env.ContentRootPath).Returns(Directory.GetCurrentDirectory()); // mock CoreSettings var settingSvcMock = new Mock <ISettingService>(); settingSvcMock.Setup(svc => svc.GetSettingsAsync <CoreSettings>()) .Returns(Task.FromResult(new CoreSettings { Theme = "MyTheme" })); // services themeService = new ThemeService(hostingEnvMock.Object, cache, metaRepoMock.Object, loggerTheme); widgetService = new WidgetService(metaRepoMock.Object, themeService, cache, settingSvcMock.Object, hostingEnvMock.Object, loggerWidget); }
public CacheJobsTest() { _mockPortfolio = new Mock <IPortfolio>(); var opts = Options.Create(new MemoryDistributedCacheOptions()); _cache = new MemoryDistributedCache(opts); }
public void ThrowsException_IfMultipleIdempotencyKeyHeaderExistsOnPostAndPatch(string httpMethod) { // Arrange var requestHeaders = new HeaderDictionary(); var idenpotencyKeys = new StringValues(new string[] { string.Empty, string.Empty }); requestHeaders.Add(_headerKeyName, idenpotencyKeys); var actionContext = ArrangeActionContextMock(httpMethod, requestHeaders); var actionExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), new Dictionary <string, object>(), Mock.Of <Controller>() ); // Expected error messages per .NET Target Framework: List <string> expectedExceptionMessages = new List <string>(); // .NET Core 2.0 & 2.1 Exception Message: expectedExceptionMessages.Add("Multiple Idempotency keys were found.\r\nParameter name: IdempotencyKey"); // .NET Core 3.0 Exception Message: expectedExceptionMessages.Add("Multiple Idempotency keys were found. (Parameter 'IdempotencyKey')"); var distributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var idempotencyAttributeFilter = new IdempotencyAttributeFilter(distributedCache, _loggerFactory, true, 1, _headerKeyName, _distributedCacheKeysPrefix); // Act var ex = Assert.Throws <ArgumentException>(() => idempotencyAttributeFilter.OnActionExecuting(actionExecutingContext)); // Assert (Exception message) Assert.Contains(ex.Message, expectedExceptionMessages); }
public DistributedCacheProviderTests() { var options = new OptionsWrapper <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions()); _memoryDistributedCache = new MemoryDistributedCache(options); _distributedCacheProvider = new DistributedCacheProvider(_memoryDistributedCache); }
public BlogIntegrationTestBase() { // repos var catRepo = new SqlCategoryRepository(_db); var tagRepo = new SqlTagRepository(_db); var postRepo = new SqlPostRepository(_db); // SettingService mock _settingSvcMock = new Mock <ISettingService>(); _settingSvcMock.Setup(svc => svc.GetSettingsAsync <CoreSettings>()).Returns(Task.FromResult(new CoreSettings())); _settingSvcMock.Setup(svc => svc.GetSettingsAsync <BlogSettings>()).Returns(Task.FromResult(new BlogSettings())); // MediaService mock _mediaSvcMock = new Mock <IMediaService>(); // Cache var serviceProvider = new ServiceCollection().AddMemoryCache().AddLogging().BuildServiceProvider(); var memCacheOptions = serviceProvider.GetService <IOptions <MemoryDistributedCacheOptions> >(); var cache = new MemoryDistributedCache(memCacheOptions); // LoggerFactory _loggerFactory = serviceProvider.GetService <ILoggerFactory>(); // Mapper var mapper = BlogUtil.Mapper; // Shortcode var shortcodeSvc = new Mock <IShortcodeService>(); var loggerBlogSvc = _loggerFactory.CreateLogger <BlogService>(); var mediatorMock = new Mock <IMediator>(); _blogSvc = new BlogService(_settingSvcMock.Object, catRepo, postRepo, tagRepo, cache, loggerBlogSvc, mapper, shortcodeSvc.Object, mediatorMock.Object); }
public async Task AppliesDistributedCacheSoftTimeoutAsync() { var simulatedDelayMs = 5_000; var distributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var chaosDistributedCache = new ChaosDistributedCache(distributedCache); chaosDistributedCache.SetAlwaysDelayExactly(TimeSpan.FromMilliseconds(simulatedDelayMs)); using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { using (var fusionCache = new FusionCache(new FusionCacheOptions(), memoryCache)) { fusionCache.SetupDistributedCache(chaosDistributedCache, new FusionCacheNewtonsoftJsonSerializer()); await fusionCache.SetAsync <int>("foo", 42, new FusionCacheEntryOptions().SetDurationSec(1).SetFailSafe(true)); await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); var sw = Stopwatch.StartNew(); var res = await fusionCache.GetOrSetAsync <int>("foo", async ct => throw new Exception("Sloths are cool"), new FusionCacheEntryOptions().SetDurationSec(1).SetFailSafe(true).SetDistributedCacheTimeouts(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(1_000))); sw.Stop(); Assert.Equal(42, res); Assert.True(sw.ElapsedMilliseconds >= 100, "Distributed cache soft timeout not applied"); Assert.True(sw.ElapsedMilliseconds < simulatedDelayMs, "Distributed cache soft timeout not applied"); } } }
public MultiplayerFlowTests() { MultiplayerHub.Reset(); mockDatabaseFactory = new Mock <IDatabaseFactory>(); mockDatabase = new Mock <IDatabaseAccess>(); setUpMockDatabase(); MemoryDistributedCache cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); hub = new TestMultiplayerHub(cache, mockDatabaseFactory.Object); mockGroups = new Mock <IGroupManager>(); mockContextUser1 = new Mock <HubCallerContext>(); mockContextUser1.Setup(context => context.UserIdentifier).Returns(user_id.ToString()); mockContextUser1.Setup(context => context.ConnectionId).Returns(user_id.ToString()); mockContextUser2 = new Mock <HubCallerContext>(); mockContextUser2.Setup(context => context.UserIdentifier).Returns(user_id_2.ToString()); mockContextUser2.Setup(context => context.ConnectionId).Returns(user_id_2.ToString()); Mock <IHubCallerClients <IMultiplayerClient> > mockClients = new Mock <IHubCallerClients <IMultiplayerClient> >(); mockReceiver = new Mock <IMultiplayerClient>(); mockClients.Setup(clients => clients.Group(MultiplayerHub.GetGroupId(room_id, false))).Returns(mockReceiver.Object); mockGameplayReceiver = new Mock <IMultiplayerClient>(); mockClients.Setup(clients => clients.Group(MultiplayerHub.GetGroupId(room_id, true))).Returns(mockGameplayReceiver.Object); hub.Groups = mockGroups.Object; hub.Clients = mockClients.Object; setUserContext(mockContextUser1); }
public void DistributedCacheCircuitBreakerActuallyWorks() { var circuitBreakerDuration = TimeSpan.FromSeconds(2); var distributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var chaosDistributedCache = new ChaosDistributedCache(distributedCache); using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { using (var fusionCache = new FusionCache(new FusionCacheOptions() { DistributedCacheCircuitBreakerDuration = circuitBreakerDuration }, memoryCache)) { fusionCache.DefaultEntryOptions.AllowBackgroundDistributedCacheOperations = false; fusionCache.SetupDistributedCache(chaosDistributedCache, new FusionCacheNewtonsoftJsonSerializer()); fusionCache.Set <int>("foo", 1, options => options.SetDurationSec(60).SetFailSafe(true)); chaosDistributedCache.SetAlwaysThrow(); fusionCache.Set <int>("foo", 2, options => options.SetDurationSec(60).SetFailSafe(true)); chaosDistributedCache.SetNeverThrow(); fusionCache.Set <int>("foo", 3, options => options.SetDurationSec(60).SetFailSafe(true)); Thread.Sleep(circuitBreakerDuration); memoryCache.Remove("foo"); var res = fusionCache.GetOrDefault <int>("foo", -1); Assert.Equal(1, res); } } }
public override void Initialize(string store) { lock (_lock) { if (IsInitialized) { Logger.Technical().From <MemoryCache>().Debug($"Memory Cache {store} is already initialized.").Log(); return; } Name = store; if (Container.TryResolve <IKeyValueSettings>(store, out var settings)) { if (settings.Values.ContainsKey(CompactionPercentageKey)) { if (Double.TryParse(settings.Values[CompactionPercentageKey], out var percentage)) { CompactionPercentage = percentage / 100; } } if (settings.Values.ContainsKey(SizeLimitKey)) { if (long.TryParse(settings.Values[SizeLimitKey], out var size)) { SizeLimit = size * 1024 * 1024; } } if (settings.Values.ContainsKey(SerializerNameKey)) { SerializerName = settings.Values[SerializerNameKey]; } else { SerializerName = store; } var option = new DistriOption(new MemoryDistributedCacheOptions { CompactionPercentage = CompactionPercentage, SizeLimit = SizeLimit }); DistributeCache = new MemoryDistributedCache(option); if (!Container.TryResolve <IObjectSerialization>(SerializerName, out var serializerFactory)) { SerializerFactory = Container.Resolve <IObjectSerialization>(); } else { SerializerFactory = serializerFactory; } IsInitialized = true; Logger.Technical().From <MemoryCache>().System($"Memory Cache {store} is initialized.").Log(); } } }
private Mock <IServiceProvider> GetServiceProvider(string testname) { var serviceProvider = new Mock <IServiceProvider>(); serviceProvider .Setup(x => x.GetService(typeof(IdentityService))) .Returns(new IdentityService() { Token = "Token", Username = "******" }); serviceProvider .Setup(x => x.GetService(typeof(IHttpClientService))) .Returns(new HttpClientTestService()); serviceProvider .Setup(x => x.GetService(typeof(InternalPurchaseOrderFacade))) .Returns(new InternalPurchaseOrderFacade(serviceProvider.Object, _dbContext(testname))); var services = new ServiceCollection(); services.AddMemoryCache(); var serviceProviders = services.BuildServiceProvider(); var memoryCache = serviceProviders.GetService <IMemoryCache>(); //var memoryCacheService = serviceProviders.GetService<IMemoryCacheManager>(); //memoryCacheService.Set(MemoryCacheConstant.Categories, new List<CategoryCOAResult>() { new CategoryCOAResult() { _id = 1 } }); var opts = Options.Create(new MemoryDistributedCacheOptions()); var cache = new MemoryDistributedCache(opts); serviceProvider .Setup(x => x.GetService(typeof(IDistributedCache))) .Returns(cache); var memoryCacheManager = new MemoryCacheManager(memoryCache); memoryCacheManager.Set(MemoryCacheConstant.Categories, new List <CategoryCOAResult>() { new CategoryCOAResult() { Id = 1 } }); serviceProvider .Setup(x => x.GetService(typeof(IMemoryCacheManager))) .Returns(memoryCacheManager); var mockCurrencyProvider = new Mock <ICurrencyProvider>(); mockCurrencyProvider .Setup(x => x.GetCurrencyByCurrencyCode(It.IsAny <string>())) .ReturnsAsync((Currency)null); serviceProvider .Setup(x => x.GetService(typeof(ICurrencyProvider))) .Returns(mockCurrencyProvider.Object); return(serviceProvider); }
public void Constructor_Cache_Null() { var memoryCache = new MemoryCache(new MemoryCacheOptions()); var distributedCache = new MemoryDistributedCache(memoryCache); IAddressRegistry addressRegistry = new AddressRegistryMock(new AddressRegistrySettings(), distributedCache); new CollaborationProtocolRegistry(new CollaborationProtocolRegistrySettings(), null, addressRegistry); }
private static DistributedCachedDataRepository DistributedCachedDataRepository(TimeSpan expiration, DataRepository dataRepository) { IDistributedCache memoryDistributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); return(new DistributedCachedDataRepository(dataRepository, memoryDistributedCache, expiration)); }
public SpectatorHubTest() { // not used for now, but left here for potential future usage. MemoryDistributedCache cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var clientStates = new EntityStore <SpectatorClientState>(); hub = new SpectatorHub(cache, clientStates); }
public InvestmentsHandlerTest() { _mockPortfolio = new Mock <IPortfolio>(); _mockTracer = new Mock <ITracer>(); _mockTracer.Setup(x => x.ActiveSpan.SetTag(It.IsAny <string>(), It.IsAny <string>())); var opts = Options.Create(new MemoryDistributedCacheOptions()); _cache = new MemoryDistributedCache(opts); }
public SpectatorFlowTests() { SpectatorHub.Reset(); // not used for now, but left here for potential future usage. MemoryDistributedCache cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); hub = new SpectatorHub(cache); }
public DistributedCacheServiceTests(TestFunctionsFixture testFunctions) { _testFunctions = testFunctions; var options = new OptionsWrapper <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions()); _memoryDistributedCache = new MemoryDistributedCache(options); _distributedCacheService = new DistributedCacheService(_memoryDistributedCache); }
public SettingServiceTest() { var serviceProvider = new ServiceCollection().AddMemoryCache().AddLogging().BuildServiceProvider(); var cache = new MemoryDistributedCache(serviceProvider.GetService <IOptions <MemoryDistributedCacheOptions> >()); var logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger <SettingService>(); metaRepoMock = new Mock <IMetaRepository>(); settingService = new SettingService(metaRepoMock.Object, cache, logger); }
public AuthCodeServiceTests() { var randomNumberGenerator = new StandardRandomNumberGenerator(); _AuthCodeGenerator = new AuthCodeGenerator(randomNumberGenerator); var cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); _AuthCodeService = new AuthCodeService(cache, _AuthCodeGenerator); }
public void MarkDuplicateAsDuplicate() { var distributedCache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions())); var duplicateChecker = new DistributedCacheDuplicateChecker(distributedCache, TimeSpan.FromMinutes(10)); duplicateChecker.IsDuplicate(12345); var isDuplicate = duplicateChecker.IsDuplicate(12345); Assert.True(isDuplicate); }