Skip to content

Commit 68d9821

Browse files
committed
Awlful plugin hack (#247)
1 parent f3e75ab commit 68d9821

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/MyTested.AspNetCore.Mvc.Caching/Plugins/CachingTestPlugin.cs

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
{
33
using System;
44
using Internal;
5+
using Internal.Contracts;
56
using Microsoft.Extensions.Caching.Memory;
67
using Microsoft.Extensions.DependencyInjection;
78
using Internal.Services;
89
using Microsoft.Extensions.Caching.Distributed;
10+
using Utilities.Validators;
911

1012
public class CachingTestPlugin : IServiceRegistrationPlugin
1113
{
@@ -15,6 +17,9 @@ public class CachingTestPlugin : IServiceRegistrationPlugin
1517
private readonly Type defaultDistributedCachingServiceType = typeof(IDistributedCache);
1618
private readonly Type defaultDistributedCachingImplementationType = typeof(MemoryDistributedCache);
1719

20+
private bool shouldReplaceMemoryCache = false;
21+
private bool shouldReplaceDistributedCache = false;
22+
1823
public Func<ServiceDescriptor, bool> ServiceSelectorPredicate
1924
=> serviceDescriptor =>
2025
{
@@ -26,6 +31,16 @@ public Func<ServiceDescriptor, bool> ServiceSelectorPredicate
2631
serviceDescriptor.ImplementationType == this.defaultCachingImplementationType ||
2732
serviceDescriptor.ImplementationType == this.defaultDistributedCachingImplementationType;
2833

34+
if (serviceDescriptor.ServiceType == this.defaultCachingServiceType)
35+
{
36+
this.shouldReplaceMemoryCache = serviceDescriptor.ImplementationType == defaultCachingImplementationType;
37+
}
38+
39+
if (serviceDescriptor.ServiceType == this.defaultDistributedCachingServiceType)
40+
{
41+
this.shouldReplaceDistributedCache = serviceDescriptor.ImplementationType == defaultDistributedCachingImplementationType;
42+
}
43+
2944

3045
return isValidServiceType && isValidImplementationType;
3146
};
@@ -36,10 +51,19 @@ public Action<IServiceCollection> ServiceRegistrationDelegate
3651
{
3752
return serviceCollection =>
3853
{
39-
serviceCollection.ReplaceMemoryCache();
40-
serviceCollection.ReplaceDistributedCache();
54+
CommonValidator.CheckForNullReference(serviceCollection);
55+
56+
if (this.shouldReplaceMemoryCache)
57+
{
58+
serviceCollection.ReplaceMemoryCache();
59+
TestHelper.GlobalTestCleanup += () => TestServiceProvider.GetService<IMemoryCache>()?.Dispose();
60+
}
4161

42-
TestHelper.GlobalTestCleanup += () => TestServiceProvider.GetService<IMemoryCache>()?.Dispose();
62+
if (this.shouldReplaceDistributedCache)
63+
{
64+
serviceCollection.ReplaceDistributedCache();
65+
TestHelper.GlobalTestCleanup += () => TestServiceProvider.GetService<IDistributedCacheMock>()?.Dispose();
66+
}
4367
};
4468
}
4569
}

0 commit comments

Comments
 (0)