Skip to content

Instantly share code, notes, and snippets.

@csharpfritz
Last active February 22, 2024 15:46
Show Gist options
  • Save csharpfritz/427d0e2747a0e3e065df7ee92fb80f6f to your computer and use it in GitHub Desktop.
Save csharpfritz/427d0e2747a0e3e065df7ee92fb80f6f to your computer and use it in GitHub Desktop.
CSV repository
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