Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

98 righe
2.6 KiB

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