SqliteConnectionFactory.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using Microsoft.Data.SqlClient;
  2. using Microsoft.Data.Sqlite;
  3. using System.Data.Common;
  4. using System.Diagnostics;
  5. namespace EVCB_OCPP.DBAPI.ConnectionFactory;
  6. public class SqliteConnectionFactory<T> : ISqliteConnectionConnectionFactory<T> where T : class
  7. {
  8. private readonly ILogger<SqliteConnectionFactory<T>> logger;
  9. public required string ConnectionString { get; init; }
  10. public SqliteConnectionFactory(ILogger<SqliteConnectionFactory<T>> logger)
  11. {
  12. this.logger = logger;
  13. }
  14. public SqliteConnection Create()
  15. {
  16. var sqlConnection = new SqliteConnection(ConnectionString);
  17. sqlConnection.Open();
  18. return sqlConnection;
  19. }
  20. public async Task<SqliteConnection> CreateAsync()
  21. {
  22. var timer = Stopwatch.StartNew();
  23. long t0, t1;
  24. var connectionStringBuilder = new SqliteConnectionStringBuilder(ConnectionString) {};
  25. var sqlConnection = new SqliteConnection(connectionStringBuilder.ToString());
  26. t0 = timer.ElapsedMilliseconds;
  27. await sqlConnection.OpenAsync();
  28. t1 = timer.ElapsedMilliseconds;
  29. timer.Stop();
  30. if (t1 > 500)
  31. {
  32. logger.LogWarning("{type} SqlConnection Open slow {create}/{open}", typeof(T), t0, t1);
  33. }
  34. return sqlConnection;
  35. }
  36. }