25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

DatabaseTestHost.cs 1.8 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Threading;
  2. using Dapper;
  3. using DotNetCore.CAP.Persistence;
  4. namespace DotNetCore.CAP.MySql.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<IStorageInitializer>();
  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. }
  57. }
  58. }
  59. }