|
2 | 2 | // The .NET Foundation licenses this file to you under the MIT license.
|
3 | 3 |
|
4 | 4 | using System;
|
| 5 | +using Microsoft.Extensions.Caching.Distributed; |
5 | 6 | using Microsoft.Extensions.Caching.Hybrid;
|
6 | 7 | using Microsoft.Extensions.Caching.Hybrid.Internal;
|
| 8 | +using Microsoft.Extensions.Caching.Memory; |
7 | 9 | using Microsoft.Extensions.DependencyInjection.Extensions;
|
| 10 | +using Microsoft.Extensions.Options; |
8 | 11 | using Microsoft.Shared.Diagnostics;
|
9 | 12 |
|
10 | 13 | namespace Microsoft.Extensions.DependencyInjection;
|
@@ -41,4 +44,35 @@ public static IHybridCacheBuilder AddHybridCache(this IServiceCollection service
|
41 | 44 | services.TryAddSingleton<HybridCache, DefaultHybridCache>();
|
42 | 45 | return new HybridCacheBuilder(services);
|
43 | 46 | }
|
| 47 | + |
| 48 | + /// <summary> |
| 49 | + /// Adds support for keyed multi-tier caching services. |
| 50 | + /// </summary> |
| 51 | + /// <returns>A builder instance that allows further configuration of the <see cref="HybridCache"/> system.</returns> |
| 52 | + public static IHybridCacheBuilder AddHybridCache(this IServiceCollection services, string name, Action<HybridCacheOptions> setupAction) |
| 53 | + { |
| 54 | + _ = Throw.IfNull(services); |
| 55 | + _ = Throw.IfNull(name); |
| 56 | + _ = Throw.IfNull(setupAction); |
| 57 | + |
| 58 | + // Register options for this key |
| 59 | + _ = services.AddOptions<HybridCacheOptions>(name).Configure(setupAction); |
| 60 | + |
| 61 | + // Register keyed in-memory cache |
| 62 | + services.TryAddKeyedSingleton<IMemoryCache, MemoryCache>(name); |
| 63 | + |
| 64 | + // Register keyed HybridCache |
| 65 | + services.TryAddKeyedSingleton<HybridCache>(name, (sp, _) => |
| 66 | + new DefaultHybridCache( |
| 67 | + Options.Options.Create(sp.GetRequiredService<IOptionsMonitor<HybridCacheOptions>>().Get(name)), |
| 68 | + sp, |
| 69 | + sp.GetKeyedService<IMemoryCache>(name), |
| 70 | + sp.GetKeyedService<IDistributedCache>(name))); |
| 71 | + |
| 72 | + services.TryAddSingleton<IHybridCacheSerializerFactory, DefaultJsonSerializerFactory>(); |
| 73 | + services.TryAddSingleton<IHybridCacheSerializer<string>>(InbuiltTypeSerializer.Instance); |
| 74 | + services.TryAddSingleton<IHybridCacheSerializer<byte[]>>(InbuiltTypeSerializer.Instance); |
| 75 | + |
| 76 | + return new HybridCacheBuilder(services); |
| 77 | + } |
44 | 78 | }
|
0 commit comments