Repository Pattern with Dapper SQL and MongoDB

Also available in portuguese

The goal is to show how to use Repository Pattern to access multiple databases. I will show an implementation of data acces using SQL Server with Dapper and another one with MongoDB ASP.NET oficial driver.

Our business class does not need to know where is the database or wich one is. Finally, we don’t need to perform changes to our business class when changing the data class.

MongoDB Repository:

public class MongoDBRepository : IDisposable
    {
        public MongoDBRepository()
            : this("localhost")
        {

        }

        public MongoDBRepository(string databaseName)
        {
            DatabaseName = databaseName;
            _client = new MongoClient();
            _database = _client.GetDatabase(DatabaseName);
        }

        public void Dispose()
        {
            _client = null;
            _database = null;
        }

        public string DatabaseName { get; set; }
        private IMongoClient _client;
        private IMongoDatabase _database;

        public IMongoDatabase Database
        {
            get
            {
                return _database;
            }
        }
    }

SQL Repository:

public class SqlServerRepository : IDisposable
    {
        public SqlServerRepository()
            : this("sqlserver")
        {

        }

        public SqlServerRepository(string connectionStringId)
        {
            _connectionStringId = connectionStringId;
        }

        public virtual string ConnnectionStringId
        {
            get
            {
                return _connectionStringId;
            }
        }

        protected SqlConnection Database
        {
            get
            {
                if (_connection == null)
                {
                    if (string.IsNullOrEmpty(_connectionString))
                    {
                        _connectionString = ConfigurationManager.ConnectionStrings[ConnnectionStringId].ConnectionString;
                    }

                    _connection = new SqlConnection(_connectionString);
                }

                return _connection;
            }
        }

        public SqlServerRepository UseConnectionStringId(string connectionStringId)
        {
            _connectionStringId = connectionStringId;

            return this;
        }

        public SqlServerRepository UseConnectionString(string connectionString)
        {
            _connectionString = connectionString;

            return this;
        }

        public virtual void Dispose()
        {
            if (_connection != null)
            {
                _connection.Close();
                _connection.Dispose();
                _connection = null;
            }
        }

        private SqlConnection _connection = null;
        private string _connectionStringId;
        private string _connectionString;
    }

Dapper Repository:

public class DapperTaxaRepository : SqlServerRepository, ITaxaRepository
    {
        public async Task<IEnumerable<Taxa>> ListarTaxa(int codigo)
        {
            var command = @"SELECT  Valor, Fator, Codigo 
                            FROM    Taxas 
                            WHERE   Codigo = @codigo";

            return await Database.QueryAsync<Taxa>(command, new { codigo = codigo });
        }
    }

Usability:

public async Task<ActionResult> Index()
        {
            // Exemplos de chamadas paralelas usando diferentes repositorios

            // Servico se vira para achar o repositorio
            var calculoA = TaxaService.CalcularTaxa(1);

            // Servico recebe o repositorio via DI
            var calculoB = TaxaService.CalcularTaxa(1, _repository);

            // Servico recebe o repositorio especifico do mongodb
            var calculoC = TaxaService.CalcularTaxa(1, new MongoDBTaxaRepository());

            await Task.WhenAll(calculoA, calculoB, calculoC);
            
            return View();
        }

This is it. I hope it helped.

Repository Pattern with Dapper SQL and MongoDB

Repository SQL Dapper MongoDB: Questions, suggestions and feedbacks will be appreciated. Good luck!

Do complete download of the source code on github.
About the Author:
He works as a solution architect and developer, has more than 16 years of experience in software development on several platforms and more than 14 years only for the insurance market.