ServiceCollectionExtensions.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. // Don't cache null values. Remove this optional setting if it's not necessary.
  27. .SkipCachingResults(result =>
  28. result.Value == null || (result.Value is EFTableRows rows && rows.RowsCount == 0)));
  29. serviceCollection.AddPooledDbContextFactory<JellyfinDb>((serviceProvider, opt) =>
  30. {
  31. var applicationPaths = serviceProvider.GetRequiredService<IApplicationPaths>();
  32. var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
  33. opt.UseSqlite($"Filename={Path.Combine(applicationPaths.DataPath, "jellyfin.db")}")
  34. .AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>())
  35. .UseLoggerFactory(loggerFactory);
  36. });
  37. return serviceCollection;
  38. }
  39. }