| | | 1 | | namespace Snacks.DAL.Common; |
| | | 2 | | |
| | | 3 | | using System.Data.Common; |
| | | 4 | | using System.Threading.Tasks; |
| | | 5 | | using Microsoft.Extensions.Configuration; |
| | | 6 | | |
| | | 7 | | public class DefaultConnectionFactory : IConnectionFactory |
| | | 8 | | { |
| | | 9 | | protected DbProviderFactory dbProviderFactory; |
| | | 10 | | |
| | | 11 | | public static IConnectionFactory FromConfiguration(IConfiguration configuration, string connectionStringConfigName) |
| | 202 | 12 | | { |
| | 202 | 13 | | (string connectionString, string providerName) = |
| | 202 | 14 | | ConfigurationUtil.GetConnectionParameters(configuration, connectionStringConfigName); |
| | 200 | 15 | | return new DefaultConnectionFactory(connectionString, providerName); |
| | 200 | 16 | | } |
| | | 17 | | |
| | 208 | 18 | | public DefaultConnectionFactory(string connectionString, string providerName) |
| | 208 | 19 | | { |
| | 208 | 20 | | this.ConnectionString = connectionString; |
| | 208 | 21 | | this.ProviderName = providerName; |
| | | 22 | | |
| | 208 | 23 | | DbUtil.RegisterAdoProviders(); |
| | 208 | 24 | | this.dbProviderFactory = DbProviderFactories.GetFactory(providerName); |
| | 208 | 25 | | } |
| | | 26 | | |
| | 334 | 27 | | public string ConnectionString { get; } |
| | | 28 | | |
| | 2 | 29 | | public string ProviderName { get; } |
| | | 30 | | |
| | | 31 | | public async Task<DbConnection> CreateConnectionAsync() |
| | 336 | 32 | | { |
| | | 33 | | |
| | 336 | 34 | | var connection = dbProviderFactory.CreateConnection(); |
| | 336 | 35 | | if (connection is null) |
| | 2 | 36 | | { |
| | 2 | 37 | | throw new InvalidOperationException("DBProviderFactory.CreateConnection() returned null"); |
| | | 38 | | } |
| | 334 | 39 | | connection.ConnectionString = ConnectionString; |
| | 334 | 40 | | await connection.OpenAsync(); |
| | | 41 | | |
| | 332 | 42 | | return connection; |
| | 332 | 43 | | } |
| | | 44 | | } |