|
| 1 | +using BitFaster.Caching.Lfu; |
| 2 | +using BitFaster.Caching.Lru; |
| 3 | +using Microsoft.Extensions.DependencyInjection; |
| 4 | +using Microsoft.Extensions.DependencyInjection.Extensions; |
| 5 | +using System; |
| 6 | + |
| 7 | +namespace BitFaster.Caching.DependencyInjection |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// Extension methods for setting up caches in an <see cref="IServiceCollection" />. |
| 11 | + /// </summary> |
| 12 | + public static class CacheExtensions |
| 13 | + { |
| 14 | + /// <summary> |
| 15 | + /// Adds a <see cref="ConcurrentLru{K,V}" />to the <see cref="IServiceCollection" />. |
| 16 | + /// </summary> |
| 17 | + /// <typeparam name="K">The type of the key.</typeparam> |
| 18 | + /// <typeparam name="V">The type of the values.</typeparam> |
| 19 | + /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param> |
| 20 | + /// <param name="configure">A delegate which can use a cache builder to build a cache.</param> |
| 21 | + /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns> |
| 22 | + public static IServiceCollection AddConcurrentLru<K, V>(this IServiceCollection services, Action<ConcurrentLruBuilder<K, V>> configure) |
| 23 | + { |
| 24 | + // this is not so simple because the builder can change the return type. |
| 25 | + |
| 26 | + var builder = new ConcurrentLruBuilder<K, V>(); |
| 27 | + configure(builder); |
| 28 | + services.TryAddSingleton<ICache<K, V>>(builder.Build()); |
| 29 | + return services; |
| 30 | + } |
| 31 | + |
| 32 | + public static IServiceCollection AddConcurrentLfu<K, V>(this IServiceCollection services, Action<ConcurrentLfuBuilder<K, V>> configure) |
| 33 | + { |
| 34 | + var builder = new ConcurrentLfuBuilder<K, V>(); |
| 35 | + configure(builder); |
| 36 | + services.TryAddSingleton<ICache<K, V>>(builder.Build()); |
| 37 | + return services; |
| 38 | + } |
| 39 | + } |
| 40 | +} |
0 commit comments