ServiceCollectionExtensions.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. /// <returns>The updated service collection.</returns>
  18. public static IServiceCollection AddJellyfinDbContext(this IServiceCollection serviceCollection)
  19. {
  20. serviceCollection.AddEFSecondLevelCache(options =>
  21. options.UseMemoryCacheProvider()
  22. .CacheAllQueries(CacheExpirationMode.Sliding, TimeSpan.FromMinutes(10))
  23. .DisableLogging(true)
  24. .UseCacheKeyPrefix("EF_")
  25. // Don't cache null values. Remove this optional setting if it's not necessary.
  26. .SkipCachingResults(result =>
  27. result.Value is null || (result.Value is EFTableRows rows && rows.RowsCount == 0)));
  28. serviceCollection.AddPooledDbContextFactory<JellyfinDbContext>((serviceProvider, opt) =>
  29. {
  30. var applicationPaths = serviceProvider.GetRequiredService<IApplicationPaths>();
  31. opt.UseSqlite($"Filename={Path.Combine(applicationPaths.DataPath, "jellyfin.db")}")
  32. .AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>());
  33. });
  34. return serviceCollection;
  35. }
  36. }