ServiceCollectionExtensions.cs 2.1 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. using Microsoft.Extensions.Logging;
  8. namespace Jellyfin.Server.Implementations.Extensions;
  9. /// <summary>
  10. /// Extensions for the <see cref="IServiceCollection"/> interface.
  11. /// </summary>
  12. public static class ServiceCollectionExtensions
  13. {
  14. /// <summary>
  15. /// Adds the <see cref="IDbContextFactory{TContext}"/> interface to the service collection with second level caching enabled.
  16. /// </summary>
  17. /// <param name="serviceCollection">An instance of the <see cref="IServiceCollection"/> interface.</param>
  18. /// <returns>The updated service collection.</returns>
  19. public static IServiceCollection AddJellyfinDbContext(this IServiceCollection serviceCollection)
  20. {
  21. serviceCollection.AddEFSecondLevelCache(options =>
  22. options.UseMemoryCacheProvider()
  23. .CacheAllQueries(CacheExpirationMode.Sliding, TimeSpan.FromMinutes(10))
  24. .DisableLogging(true)
  25. .UseCacheKeyPrefix("EF_")
  26. .SkipCachingCommands(commandText =>
  27. commandText.Contains("NEWID()", StringComparison.InvariantCultureIgnoreCase))
  28. // Don't cache null values. Remove this optional setting if it's not necessary.
  29. .SkipCachingResults(result =>
  30. result.Value == null || (result.Value is EFTableRows rows && rows.RowsCount == 0)));
  31. serviceCollection.AddPooledDbContextFactory<JellyfinDb>((serviceProvider, opt) =>
  32. {
  33. var applicationPaths = serviceProvider.GetRequiredService<IApplicationPaths>();
  34. var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
  35. opt.UseSqlite($"Filename={Path.Combine(applicationPaths.DataPath, "jellyfin.db")}")
  36. .AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>())
  37. .UseLoggerFactory(loggerFactory);
  38. });
  39. return serviceCollection;
  40. }
  41. }