Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Kritner
Created January 5, 2019 02:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kritner/f84f1d103b76af6b12f7a76e56435b54 to your computer and use it in GitHub Desktop.
Save Kritner/f84f1d103b76af6b12f7a76e56435b54 to your computer and use it in GitHub Desktop.
DB Connection .net core
public interface IDbConnectionFactory
{
IDbConnection Get(string connectionString);
}
public interface ISuperService
{
void DoStuff();
}
public class MySuperService : ISuperService
{
private readonly IDbConnectionFactory _dbConnectionFactory;
public MySuperService(IDbConnectionFactory dbConnectionFactory)
{
_dbConnectionFactory = dbConnectionFactory;
}
public void DoStuff()
{
using (var conn = _connectionFactory.Get(_connectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "mySuperAwesomeStoredProc";
cmd.CommandType = CommandType.StoredProcedure;
cmd.AddParameter("someParam", 42);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Some record was returned");
}
}
}
}
}
}
public class SqlDbConnectionFactory : IDbConnectionFactory
{
public IDbConnection Get(string connectionString)
{
return new SqlConnection(connectionString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment