Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

DatabaseTestHost.cs 1.8 KiB

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