ServiceCollectionExtensions.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. .UseCacheKeyPrefix("EF_")
  24. // Don't cache null values. Remove this optional setting if it's not necessary.
  25. .SkipCachingResults(result => result.Value is null or EFTableRows { RowsCount: 0 }));
  26. serviceCollection.AddPooledDbContextFactory<JellyfinDbContext>((serviceProvider, opt) =>
  27. {
  28. var applicationPaths = serviceProvider.GetRequiredService<IApplicationPaths>();
  29. opt.UseSqlite($"Filename={Path.Combine(applicationPaths.DataPath, "jellyfin.db")}")
  30. .AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>());
  31. });
  32. return serviceCollection;
  33. }
  34. }