- Add placeholder User entity - Add DataAccess class with interface and add it as a service to the app. - Change background color of app as a test
65 lines
1.6 KiB
C#
65 lines
1.6 KiB
C#
using Dapper;
|
|
using WretchedMachines.DataAccess.Entities;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Npgsql;
|
|
|
|
namespace WretchedMachines.DataAccess;
|
|
|
|
public class DataAccess: IDataAccess, IDisposable
|
|
{
|
|
private readonly NpgsqlConnection connection;
|
|
private readonly IMemoryCache cache;
|
|
private bool disposedValue;
|
|
|
|
|
|
public DataAccess(IConfiguration configuration, IMemoryCache cache)
|
|
{
|
|
var connectionString = configuration.GetConnectionString("Default");
|
|
this.cache = cache;
|
|
connection = new NpgsqlConnection(connectionString);
|
|
connection.Open();
|
|
}
|
|
|
|
public IEnumerable<User>? GetUser(int id)
|
|
{
|
|
var users = GetFromCache<User>("select * from users");
|
|
return users?.Where(u => id == u.Id);
|
|
}
|
|
|
|
protected virtual void Dispose(bool disposing)
|
|
{
|
|
if(!disposedValue){
|
|
if(disposing){
|
|
connection?.Dispose();
|
|
}
|
|
disposedValue = true;
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Dispose(disposing: true);
|
|
GC.SuppressFinalize(true);
|
|
}
|
|
|
|
private IEnumerable<T> GetFromDb<T>(string sql)
|
|
{
|
|
return connection.Query<T>(sql);
|
|
}
|
|
|
|
private IEnumerable<T>? GetFromCache<T>(string sql)
|
|
{
|
|
var cacheKey = typeof(T).Name;
|
|
IEnumerable<T>? entities = null;
|
|
if(cache.TryGetValue(cacheKey, out entities))
|
|
{
|
|
return entities;
|
|
}
|
|
|
|
entities = GetFromDb<T>(sql);
|
|
cache.Set(cacheKey, entities);
|
|
return entities;
|
|
}
|
|
}
|