Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

97 Zeilen
2.6 KiB

  1. using System;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.DependencyInjection;
  4. namespace DotNetCore.CAP.EntityFrameworkCore.Test
  5. {
  6. public abstract class TestHost : IDisposable
  7. {
  8. protected IServiceCollection _services;
  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. var connectionString = ConnectionUtil.GetConnectionString();
  25. //services.AddSingleton(new SqlServerOptions { ConnectionString = connectionString });
  26. //services.AddDbContext<TestDbContext>(options => options.UseSqlServer(connectionString));
  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. }