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.

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