You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

97 lines
2.5 KiB

  1. using System;
  2. using Microsoft.Extensions.DependencyInjection;
  3. namespace DotNetCore.CAP.PostgreSql.Test
  4. {
  5. public abstract class TestHost : IDisposable
  6. {
  7. protected IServiceCollection _services;
  8. protected string _connectionString;
  9. private IServiceProvider _provider;
  10. private IServiceProvider _scopedProvider;
  11. public TestHost()
  12. {
  13. CreateServiceCollection();
  14. PreBuildServices();
  15. BuildServices();
  16. PostBuildServices();
  17. }
  18. protected IServiceProvider Provider => _scopedProvider ?? _provider;
  19. private void CreateServiceCollection()
  20. {
  21. var services = new ServiceCollection();
  22. services.AddOptions();
  23. services.AddLogging();
  24. _connectionString = ConnectionUtil.GetConnectionString();
  25. services.AddSingleton(new PostgreSqlOptions { ConnectionString = _connectionString });
  26. services.AddSingleton<PostgreSqlStorage>();
  27. _services = services;
  28. }
  29. protected virtual void PreBuildServices()
  30. {
  31. }
  32. private void BuildServices()
  33. {
  34. _provider = _services.BuildServiceProvider();
  35. }
  36. protected virtual void PostBuildServices()
  37. {
  38. }
  39. public IDisposable CreateScope()
  40. {
  41. var scope = CreateScope(_provider);
  42. var loc = scope.ServiceProvider;
  43. _scopedProvider = loc;
  44. return new DelegateDisposable(() =>
  45. {
  46. if (_scopedProvider == loc)
  47. {
  48. _scopedProvider = null;
  49. }
  50. scope.Dispose();
  51. });
  52. }
  53. public IServiceScope CreateScope(IServiceProvider provider)
  54. {
  55. var scope = provider.GetService<IServiceScopeFactory>().CreateScope();
  56. return scope;
  57. }
  58. public T GetService<T>() => Provider.GetService<T>();
  59. public T Ensure<T>(ref T service)
  60. where T : class
  61. => service ?? (service = GetService<T>());
  62. public virtual void Dispose()
  63. {
  64. (_provider as IDisposable)?.Dispose();
  65. }
  66. private class DelegateDisposable : IDisposable
  67. {
  68. private Action _dispose;
  69. public DelegateDisposable(Action dispose)
  70. {
  71. _dispose = dispose;
  72. }
  73. public void Dispose()
  74. {
  75. _dispose();
  76. }
  77. }
  78. }
  79. }