使用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;
}
}
这是要走的路吗?我应该在构造函数中加载帖子吗?