Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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