一次从文件中读取内容...静态还是单例?

使用ASP.NET Core 3.0,我有一个PostService,可以读取一些Markdown文件的内容:

public class PostService : IPostService {

  private String _basePath;

  public PostService(IWebHostEnvironment _webHostEnvironment) {
    _basePath = _webHostEnvironment.WebRootPath;      
  }

  public async Task<IList<Post>> GetallAsync() {

    IList<Post> _posts = new List<Post>();

    String[] files = Directory.GetFiles($"{_basePath}/posts","*",SearchOption.AllDirectories);

    foreach (String file in files) {

      String content = await File.ReadAllTextAsync(file);

      // Process content and create 'post' from content 

      _posts.Add(post);

    }

    return _posts;

  }

}

然后在控制器上按如下方式使用它:

public class PostController : ControllerBase {   

    public PostController(IPostService postService) {
      _postService = postService;      
    }

    [HttpGet("posts/{id}")]
    public async Task<IactionResult> Get(Int32 id) {

      Post post = _postService.GetallAsync().FirstOrDefault(x => x.Id == id);

      // Remaining code
    } 
}

我不想在每个请求中都加载文件,因为它们不会更改。

我应该将PostService添加为Singleton吗?

services.AddSingleton<IPostService,PostService>();   

我应该将帖子存储在PostService中的静态变量中吗?

避免始终加载和读取文件的最佳方法是什么?

更新

在PostService中使用静态字段将类似于:

public class PostService : IPostService {

  private static List<Post>() _posts;

  private String _basePath;

  public PostService(IWebHostEnvironment _webHostEnvironment) {
    _basePath = _webHostEnvironment.WebRootPath;      
  }

  public async Task<IList<Post>> GetallAsync() {

    // Check if Posts were already loaded.
    if (_posts != null)
      return _posts; // If yes then return _posts and do not load files

    String[] files = Directory.GetFiles($"{_basePath}/posts",SearchOption.AllDirectories);

    foreach (String file in files) {

      String content = await File.ReadAllTextAsync(file);

      // Process content and create 'post' from content 

      _posts.Add(post);

    }

    return _posts;

  }

}

这是要走的路吗?我应该在构造函数中加载帖子吗?

zhuguanglu 回答:一次从文件中读取内容...静态还是单例?

如果将类设置为单例,则将其永远谴责为单例。该类(我假设)将做的不仅仅是存储帖子。您可能会发现,您需要它不是单例对象。

我会将列表存储为静态变量。

还有其他一些方法可以将缓存的项目保存在内存中,为此目的进行了优化(例如System.Runtime.Caching.MemoryCache)。

,

我认为两个选项都可以。


  

在PostService中使用静态字段

静态构造函数开箱即用是线程安全的。延迟加载的成员需要使线程安全。

本文链接:https://www.f2er.com/3163127.html

大家都在问