Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

98 рядки
2.6 KiB

  1. using System;
  2. using Microsoft.Extensions.DependencyInjection;
  3. namespace DotNetCore.CAP.SqlServer.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 SqlServerOptions { ConnectionString = _connectionString });
  26. services.AddSingleton(new CapOptions());
  27. services.AddSingleton<SqlServerStorage>();
  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. }