Skip to content

Instantly share code, notes, and snippets.

@ariessanchezsulit
Forked from grofit/Account.cs
Created April 3, 2017 08:50
Show Gist options
  • Save ariessanchezsulit/24dd8bf7856d2610c58623a7f33d98b7 to your computer and use it in GitHub Desktop.
Save ariessanchezsulit/24dd8bf7856d2610c58623a7f33d98b7 to your computer and use it in GitHub Desktop.
A GOOD Generic Repository Pattern
public class Account
{
Guid Id {get;set;}
string Name {get;set;}
}
public class DatabaseRepository<T> : IRepository<T>
{
private IDbConnection _connection;
public DatabaseRepository(IDbConnection connection)
{ _connection = connection; }
// Crud is a given
public IEnumerable<T> Find(IFindQuery<T> query)
{ return query.Find(_connection); }
public void Execute(IExecuteQuery<T> query)
{ query.Execute(_connection); }
}
// This allows you to not have to fudge all your logic into your repository classes.
// So this stops individual Repositories like PlayerRepository : SomeRepository<Player> with custom GetAllPlayers methods
public GetAllPlayersInAccountQuery : IFindQuery<Player>
{
public Guid AccountId {get; private set;}
public GetAllPlayersInAccountQuery(Guid accountId)
{ AccountId = accountId; }
public IEnumerable<Player> Find(IDbConnection connection)
{
using(var playerQuery = connection.GetCollection<Player>())
{ return playerQuery.Where(x => x.AccountId == AccountId); }
}
}
public interface IExecuteQuery<T>
{
void Execute(IDbConnection connection);
}
public interface IFindQuery<T>
{
IEnumerable<T> Find(IDbConnection connection); // this can be abstracted further to reduce IDbConnection
}
public interface IRepository<T> // Possibly add K for key
{
T Get(int id); // you may want to use K as a generic for the key
void Update(T entity);
void Save(T entity);
void Delete(T entity);
IEnumerable<T> Find(IFindQuery<T> query);
void Execute(IExecuteQuery<T> query);
}
public class Player
{
Guid AccountId {get;set;}
Guid Id {get;set;}
string Name {get;set;}
PlayerType Type {get;set;}
}
public class SomeClass
{
private IRepository<Player> _playerRepository;
public SomeClass(IRepository<Player> playerRepository)
{
_playerRepository = playerRepository; // or if you want to ignore IoC new DatabaseRepository(new SomeConnection());
}
public void GetPlayers()
{
var currentAccount = // Get Account Somehow
var getAllPlayersInAccountQuery = new GetAllPlayersInAccountQuery(currentAccount.Id);
return _playerRepository.Find(getAllPlayersInAccountQuery);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment