feat: 更新 ICacheManager 服务

This commit is contained in:
Argo-Tianyi 2022-01-26 20:47:07 +08:00
parent 7465b7f890
commit 4035c96c83
4 changed files with 24 additions and 20 deletions

View File

@ -12,7 +12,14 @@ namespace BootstrapAdmin.Caching;
/// </summary>
public static class CacheManager
{
private static ICacheManager Cache { get; } = DefaultCacheManager.Instance;
[NotNull]
private static ICacheManager? Cache { get; set; }
/// <summary>
/// 由服务调用
/// </summary>
/// <param name="cache"></param>
internal static void Init(ICacheManager cache) => Cache = cache;
/// <summary>
/// 获得或者新建数据

View File

@ -4,6 +4,7 @@
using BootstrapAdmin.Caching;
using BootstrapAdmin.Caching.Services;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection;
@ -14,13 +15,20 @@ namespace Microsoft.Extensions.DependencyInjection;
public static class ServiceCollectionExtensions
{
/// <summary>
///
/// 注入 ICacheManager 服务
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddCacheManager(this IServiceCollection services)
{
services.TryAddSingleton<ICacheManager>(provider => DefaultCacheManager.Instance);
services.AddMemoryCache();
services.TryAddSingleton<ICacheManager>(provider =>
{
var cache = provider.GetRequiredService<IMemoryCache>();
var cacheManager = new DefaultCacheManager(cache);
CacheManager.Init(cacheManager);
return cacheManager;
});
return services;
}
}

View File

@ -10,20 +10,12 @@ namespace BootstrapAdmin.Caching.Services;
class DefaultCacheManager : ICacheManager
{
[NotNull]
private MemoryCache? Cache { get; set; }
private IMemoryCache? Cache { get; set; }
/// <summary>
///
/// </summary>
private DefaultCacheManager()
{
Init();
}
private void Init()
{
Cache = new MemoryCache(new MemoryCacheOptions());
}
public DefaultCacheManager(IMemoryCache cache) => Cache = cache;
/// <summary>
///
@ -77,17 +69,11 @@ class DefaultCacheManager : ICacheManager
{
if (!string.IsNullOrEmpty(key))
{
// 通过 TokenManager 管理依赖
Cache.Remove(key);
}
else
{
Cache.Compact(100);
//Cache.Compact(100);
}
}
#region
[NotNull]
internal static ICacheManager? Instance { get; } = new DefaultCacheManager();
#endregion
}

View File

@ -28,6 +28,9 @@ public static class ApplicationBuilderExtensions
builder.UseSwagger(builder.Configuration["SwaggerPathBase"].TrimEnd('/'));
// 激活 ICacheManager
builder.Services.GetRequiredService<BootstrapAdmin.Caching.ICacheManager>();
return builder;
}
}