No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

DatabaseTestHost.cs 1.8 KiB

hace 7 años
hace 7 años
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Threading;
  2. using Dapper;
  3. using Microsoft.EntityFrameworkCore;
  4. namespace DotNetCore.CAP.PostgreSql.Test
  5. {
  6. public abstract class DatabaseTestHost : TestHost
  7. {
  8. private static bool _sqlObjectInstalled;
  9. public static object _lock = new object();
  10. protected override void PostBuildServices()
  11. {
  12. base.PostBuildServices();
  13. lock (_lock)
  14. {
  15. if (!_sqlObjectInstalled)
  16. {
  17. InitializeDatabase();
  18. }
  19. }
  20. }
  21. public override void Dispose()
  22. {
  23. DeleteAllData();
  24. base.Dispose();
  25. }
  26. private void InitializeDatabase()
  27. {
  28. using (CreateScope())
  29. {
  30. var storage = GetService<PostgreSqlStorage>();
  31. var token = new CancellationTokenSource().Token;
  32. CreateDatabase();
  33. storage.InitializeAsync(token).GetAwaiter().GetResult();
  34. _sqlObjectInstalled = true;
  35. }
  36. }
  37. private void CreateDatabase()
  38. {
  39. var masterConn = ConnectionUtil.GetMasterConnectionString();
  40. var databaseName = ConnectionUtil.GetDatabaseName();
  41. using (var connection = ConnectionUtil.CreateConnection(masterConn))
  42. {
  43. connection.Execute($@"
  44. DROP DATABASE IF EXISTS ""{databaseName}"";
  45. CREATE DATABASE ""{databaseName}"";");
  46. }
  47. }
  48. private void DeleteAllData()
  49. {
  50. var conn = ConnectionUtil.GetConnectionString();
  51. using (var connection = ConnectionUtil.CreateConnection(conn))
  52. {
  53. connection.Execute($@"
  54. TRUNCATE TABLE ""cap"".""published"";
  55. TRUNCATE TABLE ""cap"".""received"";
  56. TRUNCATE TABLE ""cap"".""queue"";");
  57. }
  58. }
  59. }
  60. }