Created
January 5, 2019 02:45
-
-
Save Kritner/f84f1d103b76af6b12f7a76e56435b54 to your computer and use it in GitHub Desktop.
DB Connection .net core
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
public interface IDbConnectionFactory | |
{ | |
IDbConnection Get(string connectionString); | |
} |
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
public interface ISuperService | |
{ | |
void DoStuff(); | |
} |
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
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"); | |
} | |
} | |
} | |
} | |
} | |
} |
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
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