如何在 Blazor Server 启动时获取并缓存 IStringLocalizer 的数据?

问题描述 投票:0回答:0

我想使用 Azure blob 作为

IStringLocalizer
的资源文件,而不是本地存储的
.resx
文件。但是当我尝试获取
IStringLocalizer
内的数据时,有时由于异步行为,数据不可用。因此,有时我不会收到翻译。所以我想在启动时加载
blob
并使用单例服务缓存它。然后
IStringLocalizer
可以使用该缓存服务中的数据。我找到了 2 种方法来实现我的解决方案。

选项01:

services.AddSingleton<IMyCache, MyCacheService>(options => {
   var myCacheService = new MyCacheService();
   myCacheService.LoadAsync().GetAwaiter().GetResult(); // It will fetch the blob and update the cache inside LoadAsync() method
   return myCacheService;
});

在这种方法中,我觉得通过执行

GetAwaiter().GetResult()
来阻塞线程并不好。这可能会导致死锁。但这可以确保为所需的服务加载和缓存数据。

选项 02:使用 IHostedService

public class BlobCacheService : IHostedService
{
    private readonly IBlobStorageClient _blobClient;
    private readonly ICacheRepository _cacheRepository;
    private readonly ILogger<BlobCacheService> _logger;

    public BlobCacheService(IBlobStorageClient blobClient, ICacheRepository cacheRepository, ILogger<BlobCacheService> logger)
    {
        _blobClient = blobClient;
        _cacheRepository = cacheRepository;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (!_cacheRepository.HasCachedData())
        {
            try
            {
                var blobData = await _blobClient.DownloadBlobAsync("your-blob-name");
                await _cacheRepository.SetCachedDataAsync(blobData);
                _logger.LogInformation("Blob data successfully fetched and cached.");
            }
            catch (Exception ex)
            {
                _logger.LogError("Error fetching or caching blob data: {0}", ex.Message);
            }
        }
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        // Stop any background operations
    }
}

启动.cs

services.AddHostedService<BlobCacheService>();

services.AddSingleton<IHostedService, BlobCacheService>();

services.AddHostedService<BlobCacheService>(p => new BlobCacheService(
    p.GetRequiredService<IBlobStorageClient>(),
    p.GetRequiredService<ICacheRepository>(),
    p.GetRequiredService<ILogger<BlobCacheService>>()));

但在这种情况下,它将在单独的线程中异步运行该进程。但这是否确认数据将在

IStringLocalizer
消耗之前从启动时加载?

如果有其他合适的解决方案,您能帮忙吗?或建议?

c# asynchronous caching localization blazor
© www.soinside.com 2019 - 2024. All rights reserved.