選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

100 行
2.7 KiB

  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. }