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.
 
 
 

99 regels
2.6 KiB

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