SqlConnectionFactory.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using Microsoft.EntityFrameworkCore;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using Microsoft.Data.SqlClient;
  11. namespace EVCB_OCPP.Domain.ConnectionFactory;
  12. public class SqlConnectionFactory<T> : ISqlConnectionFactory<T> where T : DbContext
  13. {
  14. private readonly ILogger<SqlConnectionFactory<T>> logger;
  15. public string ConnectionString { get; init; }
  16. public SqlConnectionFactory(ILogger<SqlConnectionFactory<T>> logger)
  17. {
  18. this.logger = logger;
  19. }
  20. public SqlConnection Create()
  21. {
  22. var sqlConnection = new SqlConnection(ConnectionString);
  23. sqlConnection.Open();
  24. return sqlConnection;
  25. }
  26. public async Task<SqlConnection> CreateAsync()
  27. {
  28. var timer = Stopwatch.StartNew();
  29. long t0, t1;
  30. var sqlConnection = new SqlConnection(ConnectionString);
  31. t0 = timer.ElapsedMilliseconds;
  32. await sqlConnection.OpenAsync();
  33. t1 = timer.ElapsedMilliseconds;
  34. timer.Stop();
  35. if (t1 > 500)
  36. {
  37. logger.LogWarning("{type} SqlConnection Open slow {create}/{open}", typeof(T), t0, t1);
  38. }
  39. return sqlConnection;
  40. }
  41. }