Skip to content

Instantly share code, notes, and snippets.

@MrDustpan
Created September 4, 2015 17:17
Show Gist options
  • Save MrDustpan/85186ca6bd9a4fb2043c to your computer and use it in GitHub Desktop.
Save MrDustpan/85186ca6bd9a4fb2043c to your computer and use it in GitHub Desktop.
Command/query implementation with async methods
using System.Data;
namespace CommandQuery
{
public interface ICommand
{
Task ExecuteAsync(IDbConnection db);
}
public interface IQuery<T>
{
Task<T> ExecuteAsync(IDbConnection db);
}
public interface IDatabase
{
Task<T> ExecuteAsync<T>(IQuery<T> query);
Task ExecuteAsync(ICommand command);
}
public class SqlDatabase : IDatabase
{
private readonly string connectionString;
public SqlDatabase(string connectionString)
{
this.connectionString = connectionString;
}
public async Task<T> Execute<T>(IQuery<T> query)
{
using (var db = await GetConnection())
{
return await query.ExecuteAsync(db);
}
}
public async Task Execute(ICommand command)
{
using (var db = await GetConnection())
{
await command.ExecuteAsync(db);
}
}
private async Task<IDbConnection> GetConnection()
{
var connection = new SqlConnection(connectionString);
return await connection.OpenAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment