Last active
February 22, 2024 15:46
-
-
Save csharpfritz/427d0e2747a0e3e065df7ee92fb80f6f to your computer and use it in GitHub Desktop.
CSV repository
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class PostRepository | |
{ | |
public PostRepository(IWebHostEnvironment env, IMemoryCache cache) | |
{ | |
Env = env; | |
_Cache = cache; | |
} | |
public IHostEnvironment Env { get; } | |
private const string POST_CACHE_KEY = "post_data"; | |
private readonly IMemoryCache _Cache; | |
private IEnumerable<PostModel> GetPostsFromDisk() | |
{ | |
// open the posts.csv file from the wwwroot folder using linq2csv | |
var context = new LINQtoCSV.CsvContext(); | |
return context.Read<Post>(Path.Combine(Env.ContentRootPath, "wwwroot", "posts", "posts.csv"), new CsvFileDescription | |
{ | |
SeparatorChar = ',', | |
FirstLineHasColumnNames = true, | |
QuoteAllFields = true, | |
UseFieldIndexForReadingData = true, | |
IgnoreUnknownColumns = true | |
}).Select(p => (PostModel)p) | |
.ToArray(); | |
} | |
public PostModel[] GetPosts() | |
{ | |
return _Cache.GetOrCreate<PostModel[]>(POST_CACHE_KEY, entry => { | |
entry.SlidingExpiration = TimeSpan.FromMinutes(30); | |
return GetPostsFromDisk().ToArray(); | |
})!; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment