Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

TestHost.cs 2.6 KiB

il y a 7 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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.AddOptions<CapOptions>();
  26. services.Configure<PostgreSqlOptions>(x => x.ConnectionString = _connectionString);
  27. services.AddSingleton<PostgreSqlStorage>();
  28. _services = services;
  29. }
  30. protected virtual void PreBuildServices()
  31. {
  32. }
  33. private void BuildServices()
  34. {
  35. _provider = _services.BuildServiceProvider();
  36. }
  37. protected virtual void PostBuildServices()
  38. {
  39. }
  40. public IDisposable CreateScope()
  41. {
  42. var scope = CreateScope(_provider);
  43. var loc = scope.ServiceProvider;
  44. _scopedProvider = loc;
  45. return new DelegateDisposable(() =>
  46. {
  47. if (_scopedProvider == loc)
  48. {
  49. _scopedProvider = null;
  50. }
  51. scope.Dispose();
  52. });
  53. }
  54. public IServiceScope CreateScope(IServiceProvider provider)
  55. {
  56. var scope = provider.GetService<IServiceScopeFactory>().CreateScope();
  57. return scope;
  58. }
  59. public T GetService<T>() => Provider.GetService<T>();
  60. public T Ensure<T>(ref T service)
  61. where T : class
  62. => service ?? (service = GetService<T>());
  63. public virtual void Dispose()
  64. {
  65. (_provider as IDisposable)?.Dispose();
  66. }
  67. private class DelegateDisposable : IDisposable
  68. {
  69. private Action _dispose;
  70. public DelegateDisposable(Action dispose)
  71. {
  72. _dispose = dispose;
  73. }
  74. public void Dispose()
  75. {
  76. _dispose();
  77. }
  78. }
  79. }
  80. }