Home > front end >  FileSystem.Current.OpenAppPackageFileAsync versus FileSystemOpenAppPackageFileAsync
FileSystem.Current.OpenAppPackageFileAsync versus FileSystemOpenAppPackageFileAsync

Time:11-11

Why do some other people need to use Current (as in Version A)?

// Version A
using var stream = await FileSystem.Current.OpenAppPackageFileAsync("monkeys.json");

// Version B
using var stream = await FileSystem.OpenAppPackageFileAsync("monkeys.json");

Here is the detail:

public interface IFileSystem
{
    string CacheDirectory { get; }
    string AppDataDirectory { get; }

    Task<bool> AppPackageFileExistsAsync(string filename);
    Task<Stream> OpenAppPackageFileAsync(string filename);
}

public static class FileSystem
{
    public static string CacheDirectory { get; }

    public static string AppDataDirectory { get; }
    public static IFileSystem Current { get; }

    public static Task<bool> AppPackageFileExistsAsync(string filename);

    public static Task<Stream> OpenAppPackageFileAsync(string filename);
}

CodePudding user response:

This is probably a little leftover from the history that took place here. Historically, Xamarin.Essentials did not have (great) support for dependency injection.

For .NET MAUI, we did add that, however, we also wanted to make sure the people not using dependency injection could still use it the way they like. That's why all Essentials APIs now have a Current or Default static instance that you can access, alongside the interface version you can use with dependency injection.

In this concrete case there is zero difference. See below the source of FileSystem at the time of writing (omitted non-relevant code):

public static class FileSystem
{
    public static Task<Stream> OpenAppPackageFileAsync(string filename)
        => Current.OpenAppPackageFileAsync(filename);

    public static Task<bool> AppPackageFileExistsAsync(string filename)
        => Current.AppPackageFileExistsAsync(filename);

    static IFileSystem? currentImplementation;

    public static IFileSystem Current =>
        currentImplementation ??= new FileSystemImplementation();

    internal static void SetCurrent(IFileSystem? implementation) =>
        currentImplementation = implementation;
}

Here you can see that the FileSystem.OpenAppPackageFileAsync just calls the Current.OpenAppPackageFileAsync underneat

  • Related