Created
September 4, 2015 17:17
-
-
Save MrDustpan/85186ca6bd9a4fb2043c to your computer and use it in GitHub Desktop.
Command/query implementation with async methods
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
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