ServiceCollectionExtensions.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.IO;
  3. using EFCoreSecondLevelCacheInterceptor;
  4. using MediaBrowser.Common.Configuration;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.DependencyInjection;
  7. namespace Jellyfin.Server.Implementations.Extensions;
  8. /// <summary>
  9. /// Extensions for the <see cref="IServiceCollection"/> interface.
  10. /// </summary>
  11. public static class ServiceCollectionExtensions
  12. {
  13. /// <summary>
  14. /// Adds the <see cref="IDbContextFactory{TContext}"/> interface to the service collection with second level caching enabled.
  15. /// </summary>
  16. /// <param name="serviceCollection">An instance of the <see cref="IServiceCollection"/> interface.</param>
  17. /// <param name="disableSecondLevelCache">Whether second level cache disabled..</param>
  18. /// <returns>The updated service collection.</returns>
  19. public static IServiceCollection AddJellyfinDbContext(this IServiceCollection serviceCollection, bool disableSecondLevelCache)
  20. {
  21. if (!disableSecondLevelCache)
  22. {
  23. serviceCollection.AddEFSecondLevelCache(options =>
  24. options.UseMemoryCacheProvider()
  25. .CacheAllQueries(CacheExpirationMode.Sliding, TimeSpan.FromMinutes(10))
  26. .UseCacheKeyPrefix("EF_")
  27. // Don't cache null values. Remove this optional setting if it's not necessary.
  28. .SkipCachingResults(result => result.Value is null or EFTableRows { RowsCount: 0 }));
  29. }
  30. serviceCollection.AddPooledDbContextFactory<JellyfinDbContext>((serviceProvider, opt) =>
  31. {
  32. var applicationPaths = serviceProvider.GetRequiredService<IApplicationPaths>();
  33. var dbOpt = opt.UseSqlite($"Filename={Path.Combine(applicationPaths.DataPath, "jellyfin.db")}");
  34. if (!disableSecondLevelCache)
  35. {
  36. dbOpt.AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>());
  37. }
  38. });
  39. return serviceCollection;
  40. }
  41. }