Skip to content

Commit

Permalink
Fix issue:DiskCache is null within the ImageService object. #20
Browse files Browse the repository at this point in the history
  • Loading branch information
microspaze committed Mar 26, 2024
1 parent fca7dd1 commit 3ad8fd2
Show file tree
Hide file tree
Showing 52 changed files with 265 additions and 204 deletions.
2 changes: 2 additions & 0 deletions samples/Sample/Pages/BasicPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
Aspect="AspectFill" IsVisible="true"
AutomationProperties.IsInAccessibleTree="False">
</Image>

<Button Text="Invalidate Cache" Clicked="InvalidateCache" ></Button>
</StackLayout>
</ScrollView>
</ContentPage.Content>
Expand Down
18 changes: 17 additions & 1 deletion samples/Sample/Pages/BasicPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
using System;
using System.Collections.Generic;
using FFImageLoading;

namespace Sample
{
public partial class BasicPage : ContentPage
{
BasicPageModel viewModel;

private readonly IImageService _imageService = FFImageLoading.Helpers.ServiceHelper.GetService<IImageService>();

public BasicPage()
{
InitializeComponent();
BindingContext = viewModel = new BasicPageModel();

}

protected override void OnAppearing()
Expand All @@ -20,5 +22,19 @@ protected override void OnAppearing()

viewModel.Reload();
}

/// <summary>
/// Clear All Image Cache
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void InvalidateCache(object sender, EventArgs e)
{
if (_imageService == ImageService.Instance)
{
_imageService.InvalidateMemoryCache();
await _imageService.InvalidateDiskCacheAsync();
}
}
}
}
2 changes: 1 addition & 1 deletion samples/Sample/Pages/ByteArrayListPageModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public async void Reload()
"https://farm4.staticflickr.com/3201/3070391067_c80fb9e942.jpg"
};

var imageService = MauiProgram.Services.GetRequiredService<IImageService<TImageContainer>>();
var imageService = MauiProgram.Services.GetRequiredService<IImageService>();

for (int j = 0; j < 5; j++)
{
Expand Down
1 change: 0 additions & 1 deletion samples/Sample/Sample.Win.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,6 @@

<ItemGroup>
<ProjectReference Include="..\..\source\FFImageLoading.Maui\FFImageLoading.Maui.csproj" />
<ProjectReference Include="..\..\source\Tests\FFImageLoading.Tests.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions source/FFImageLoading.Maui/CachedImage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected static bool IsDesignModeEnabled

private bool _reloadBecauseOfMissingSize;

protected IImageService<TImageContainer> ImageService { get; private set; }
protected IImageService ImageService { get; private set; }


/// <summary>
Expand All @@ -64,7 +64,7 @@ public CachedImage()
_visualProperty.SetValue(this, _visualMarkerProperty.GetValue(null));
}

ImageService = this.FindMauiContext()?.Services?.GetRequiredService<IImageService<TImageContainer>>();
ImageService = this.FindMauiContext()?.Services?.GetRequiredService<IImageService>();
}

internal IMauiContext FindMauiContext()
Expand All @@ -85,7 +85,7 @@ protected override void OnHandlerChanged()
{
base.OnHandlerChanged();

ImageService = this.FindMauiContext()?.Services?.GetRequiredService<IImageService<TImageContainer>>();
ImageService = this.FindMauiContext()?.Services?.GetRequiredService<IImageService>();
if (ImageService != null)
{
ReloadImage();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static class TaskParameterExtensions
/// </summary>
/// <param name="parameters">Image parameters.</param>
/// <param name="cacheType">Cache type.</param>
public static async Task InvalidateAsync<TImageContainer>(this TaskParameter parameters, CacheType cacheType, IImageService<TImageContainer> imageService)
public static async Task InvalidateAsync<TImageContainer>(this TaskParameter parameters, CacheType cacheType, IImageService imageService)
{
using (var task = imageService.CreateTask(parameters))
{
Expand All @@ -30,7 +30,7 @@ public static async Task InvalidateAsync<TImageContainer>(this TaskParameter par
/// Preloads the image request into memory cache/disk cache for future use.
/// </summary>
/// <param name="parameters">Image parameters.</param>
public static IImageLoaderTask Preload<TImageContainer>(this TaskParameter parameters, IImageService<TImageContainer> imageService)
public static IImageLoaderTask Preload(this TaskParameter parameters, IImageService imageService)
{
if (parameters.Priority == null)
{
Expand All @@ -48,7 +48,7 @@ public static IImageLoaderTask Preload<TImageContainer>(this TaskParameter param
/// IMPORTANT: It throws image loading exceptions - you should handle them
/// </summary>
/// <param name="parameters">Image parameters.</param>
public static Task PreloadAsync<TImageContainer>(this TaskParameter parameters, IImageService<TImageContainer> imageService)
public static Task PreloadAsync(this TaskParameter parameters, IImageService imageService)
{
var tcs = new TaskCompletionSource<IScheduledWork>();

Expand Down Expand Up @@ -85,7 +85,7 @@ public static Task PreloadAsync<TImageContainer>(this TaskParameter parameters,
/// Only Url Source supported.
/// </summary>
/// <param name="parameters">Image parameters.</param>
public static IImageLoaderTask DownloadOnly<TImageContainer>(this TaskParameter parameters, IImageService<TImageContainer> imageService)
public static IImageLoaderTask DownloadOnly<TImageContainer>(this TaskParameter parameters, IImageService imageService)
{
if (parameters.SourceType == Work.ImageSourceType.Url)
{
Expand All @@ -101,7 +101,7 @@ public static IImageLoaderTask DownloadOnly<TImageContainer>(this TaskParameter
/// IMPORTANT: It throws image loading exceptions - you should handle them
/// </summary>
/// <param name="parameters">Image parameters.</param>
public async static Task DownloadOnlyAsync<TImageContainer>(this TaskParameter parameters, IImageService<TImageContainer> imageService)
public async static Task DownloadOnlyAsync<TImageContainer>(this TaskParameter parameters, IImageService imageService)
{
if (parameters.SourceType == Work.ImageSourceType.Url)
{
Expand Down
35 changes: 35 additions & 0 deletions source/FFImageLoading.Maui/Foundations/Helpers/ServiceHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FFImageLoading.Helpers
{
public static class ServiceHelper
{
private static IServiceProvider _serviceProvider = null;

public static T GetService<T>() where T : class
{
var service = default(T);
var serviceProvider = GetServiceProvider();
if (serviceProvider != null)
{
service = serviceProvider.GetService<T>();
}

return service;
}

private static IServiceProvider GetServiceProvider()
{
if (_serviceProvider == null && Application.Current?.Handler?.MauiContext is not null)
{
_serviceProvider = Application.Current.Handler.MauiContext.Services;
}

return _serviceProvider;
}
}
}
6 changes: 3 additions & 3 deletions source/FFImageLoading.Maui/Foundations/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ public static void RegisterServices(this IServiceCollection services)
services.AddSingleton<IWorkScheduler, WorkScheduler>();

#if IOS || MACCATALYST
services.AddSingleton<IImageService<UIKit.UIImage>, ImageService>();
services.AddSingleton<IImageService, ImageService>();
#elif ANDROID
services.AddSingleton<IImageService<FFImageLoading.Drawables.SelfDisposingBitmapDrawable>, ImageService>();
services.AddSingleton<IImageService, ImageService>();
#elif WINDOWS
services.AddSingleton<IImageService<Microsoft.UI.Xaml.Media.Imaging.BitmapSource>, ImageService>();
services.AddSingleton<IImageService, ImageService>();
#endif

#if ANDROID || WINDOWS || IOS || MACCATALYST || TIZEN
Expand Down
18 changes: 6 additions & 12 deletions source/FFImageLoading.Maui/Foundations/ImageServiceBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,26 @@

namespace FFImageLoading
{
public abstract class ImageServiceBase<TImageContainer> : IImageService<TImageContainer>
public abstract class ImageServiceBase<TImageContainer> : IImageService
{
public ImageServiceBase(
IConfiguration configuration,
IMD5Helper mD5Helper,
IMD5Helper md5Helper,
IMiniLogger miniLogger,
IPlatformPerformance platformPerformance,
IMainThreadDispatcher mainThreadDispatcher,
IDataResolverFactory dataResolverFactory,
IDiskCache diskCache,
IDownloadCache downloadCache,
IWorkScheduler workScheduler)
{
_config = configuration;
Md5Helper = mD5Helper;
Md5Helper = md5Helper;
Logger = miniLogger;
PlatformPerformance = platformPerformance;
Dispatcher = mainThreadDispatcher;
DataResolverFactory = dataResolverFactory;
DiskCache = diskCache;
DownloadCache = downloadCache;
Scheduler = workScheduler;
}
Expand All @@ -42,7 +44,6 @@ public ImageServiceBase(
public IDiskCache DiskCache { get; }
public IWorkScheduler Scheduler { get; }
public IMD5Helper MD5Helper { get; }

public IDownloadCache DownloadCache { get; }

public abstract IMemoryCache<TImageContainer> MemoryCache { get; }
Expand All @@ -55,14 +56,7 @@ protected virtual void PlatformSpecificConfiguration(IConfiguration configuratio

protected abstract void SetTaskForTarget(IImageLoaderTask currentTask);
public abstract void CancelWorkForView(object view);

public abstract IImageLoaderTask CreateTask(TaskParameter parameters);

public abstract IImageLoaderTask CreateTask<TImageView>(TaskParameter parameters, ITarget<TImageContainer, TImageView> target) where TImageView : class;




public abstract int DpToPixels(double dp, double scale);
public abstract double PixelsToDp(double px, double scale);

Expand Down Expand Up @@ -284,5 +278,5 @@ public void Cancel(Func<TaskParameter, bool> predicate)
{
Scheduler.Cancel(task => task.Parameters != null && predicate(task.Parameters));
}
}
}
}
4 changes: 2 additions & 2 deletions source/FFImageLoading.Maui/Foundations/Svg/SvgDataResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public class SvgDataResolver<TImageContainer> : IVectorDataResolver
/// <param name="vectorHeight">Vector height.</param>
/// <param name="useDipUnits">If set to <c>true</c> use dip units.</param>
/// <param name="replaceStringMap">Replace string map.</param>
public SvgDataResolver(IImageService<TImageContainer> imageService, int vectorWidth = 0, int vectorHeight = 0, bool useDipUnits = true, Dictionary<string, string> replaceStringMap = null)
public SvgDataResolver(IImageService imageService, int vectorWidth = 0, int vectorHeight = 0, bool useDipUnits = true, Dictionary<string, string> replaceStringMap = null)
{
ImageService = imageService;
VectorWidth = vectorWidth;
Expand All @@ -70,7 +70,7 @@ public SvgDataResolver(IImageService<TImageContainer> imageService, int vectorWi
ReplaceStringMap = replaceStringMap;
}

public IImageService<TImageContainer> ImageService { get; }
public IImageService ImageService { get; }

public bool UseDipUnits { get; private set; }

Expand Down
19 changes: 7 additions & 12 deletions source/FFImageLoading.Maui/Foundations/Work/IImageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace FFImageLoading
/// FFImageLoading by Daniel Luberda
/// </summary>
[Preserve(AllMembers = true)]
public interface IImageService<TImageContainer>
public interface IImageService
{
/// <summary>
/// Gets FFImageLoading configuration
Expand All @@ -37,13 +37,13 @@ public interface IImageService<TImageContainer>

IDownloadCache DownloadCache { get; }

IMemoryCache<TImageContainer> MemoryCache { get; }
public abstract IImageLoaderTask CreateTask(TaskParameter parameters);

/// <summary>
/// Initializes FFImageLoading with a default Configuration.
/// Also forces to run disk cache cleaning routines (avoiding delay for first image loading tasks)
/// </summary>
void Initialize();
/// <summary>
/// Initializes FFImageLoading with a default Configuration.
/// Also forces to run disk cache cleaning routines (avoiding delay for first image loading tasks)
/// </summary>
void Initialize();

/// <summary>
/// Initializes FFImageLoading with a given Configuration. It allows to configure and override most of it.
Expand All @@ -52,11 +52,6 @@ public interface IImageService<TImageContainer>
/// <param name="configuration">Configuration.</param>
void Initialize(IConfiguration configuration);

IImageLoaderTask CreateTask(TaskParameter parameters);

IImageLoaderTask CreateTask<TImageView>(TaskParameter parameters, ITarget<TImageContainer, TImageView> target) where TImageView : class;


/// <summary>
/// Constructs a new TaskParameter to load an image from a file.
/// </summary>
Expand Down
20 changes: 9 additions & 11 deletions source/FFImageLoading.Maui/Foundations/Work/ImageLoaderTask.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public abstract class ImageLoaderTask<TDecoderContainer, TImageContainer, TImage
#pragma warning restore RECS0108 // Warns about static fields in generic types

public ImageLoaderTask(
IImageService<TImageContainer> imageService,
IImageService imageService,
ITarget<TImageContainer, TImageView> target,
TaskParameter parameters)
{
Expand Down Expand Up @@ -224,11 +224,9 @@ private set

public ITarget Target => PlatformTarget as ITarget;

public IConfiguration Configuration
=> ImageService.Configuration;

protected readonly IImageService<TImageContainer> ImageService;

public IConfiguration Configuration => ImageService.Configuration;
protected readonly IImageService ImageService;
protected IMemoryCache<TImageContainer> MemoryCache { get; set; }
protected CancellationTokenSource CancellationTokenSource { get; private set; }


Expand Down Expand Up @@ -436,7 +434,7 @@ await ShowPlaceholder(Parameters.LoadingPlaceholderPath, KeyForLoadingPlaceholde
{
if (Configuration.ClearMemoryCacheOnOutOfMemory && ex is OutOfMemoryException)
{
ImageService.MemoryCache.Clear();
MemoryCache.Clear();
}

if (ex is OperationCanceledException)
Expand Down Expand Up @@ -469,7 +467,7 @@ await ImageService.Dispatcher.PostAsync(() =>

private async Task<bool> TryLoadFromMemoryCacheAsync(string key, bool updateImageInformation, bool animated, bool isLoadingPlaceholder)
{
var found = ImageService.MemoryCache.Get(key);
var found = MemoryCache.Get(key);
if (found?.Item1 != null)
{
try
Expand Down Expand Up @@ -549,7 +547,7 @@ protected virtual async Task ShowPlaceholder(string path, string key, ImageSourc
}

if (loadImage != default(TImageContainer))
ImageService.MemoryCache.Add(key, loadImageData.ImageInformation, loadImage);
MemoryCache.Add(key, loadImageData.ImageInformation, loadImage);
}
finally
{
Expand Down Expand Up @@ -647,7 +645,7 @@ public async Task RunAsync()
BeforeLoading(image, false);

if (image != default(TImageContainer) && CanUseMemoryCache)
ImageService.MemoryCache.Add(Key, imageData.ImageInformation, image);
MemoryCache.Add(Key, imageData.ImageInformation, image);

ThrowIfCancellationRequested();

Expand Down Expand Up @@ -677,7 +675,7 @@ public async Task RunAsync()
{
if (Configuration.ClearMemoryCacheOnOutOfMemory && ex is OutOfMemoryException)
{
ImageService.MemoryCache.Clear();
MemoryCache.Clear();
}

ImageService.Logger.Error($"Image loading failed: {Key}", ex);
Expand Down
4 changes: 2 additions & 2 deletions source/FFImageLoading.Maui/Handlers/HandlerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ public abstract class HandlerBase<TNativeView, TImageSource> : ImageSourceServic
where TNativeView: class
where TImageSource : IImageSource
{
public HandlerBase(IImageService<TImageContainer> imageService)
public HandlerBase(IImageService imageService)
{
ImageService = imageService;
}

protected readonly IImageService<TImageContainer> ImageService;
protected readonly IImageService ImageService;

protected virtual Task<IImageLoaderTask> LoadImageAsync(IImageSourceBinding binding, IImageSource imageSource, TNativeView imageView, CancellationToken cancellationToken)
{
Expand Down
Loading

0 comments on commit 3ad8fd2

Please sign in to comment.