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 години
преди 7 години
преди 7 години
преди 7 години
преди 7 години
преди 7 години
преди 7 години
преди 7 години
преди 7 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.DependencyInjection;
  4. namespace DotNetCore.CAP.SqlServer.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.AddSingleton(new SqlServerOptions { ConnectionString = _connectionString });
  27. services.AddSingleton<SqlServerStorage>();
  28. services.AddDbContext<TestDbContext>(options => options.UseSqlServer(_connectionString));
  29. _services = services;
  30. }
  31. protected virtual void PreBuildServices()
  32. {
  33. }
  34. private void BuildServices()
  35. {
  36. _provider = _services.BuildServiceProvider();
  37. }
  38. protected virtual void PostBuildServices()
  39. {
  40. }
  41. public IDisposable CreateScope()
  42. {
  43. var scope = CreateScope(_provider);
  44. var loc = scope.ServiceProvider;
  45. _scopedProvider = loc;
  46. return new DelegateDisposable(() =>
  47. {
  48. if (_scopedProvider == loc)
  49. {
  50. _scopedProvider = null;
  51. }
  52. scope.Dispose();
  53. });
  54. }
  55. public IServiceScope CreateScope(IServiceProvider provider)
  56. {
  57. var scope = provider.GetService<IServiceScopeFactory>().CreateScope();
  58. return scope;
  59. }
  60. public T GetService<T>() => Provider.GetService<T>();
  61. public T Ensure<T>(ref T service)
  62. where T : class
  63. => service ?? (service = GetService<T>());
  64. public virtual void Dispose()
  65. {
  66. (_provider as IDisposable)?.Dispose();
  67. }
  68. private class DelegateDisposable : IDisposable
  69. {
  70. private Action _dispose;
  71. public DelegateDisposable(Action dispose)
  72. {
  73. _dispose = dispose;
  74. }
  75. public void Dispose()
  76. {
  77. _dispose();
  78. }
  79. }
  80. }
  81. }