Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

56 строки
1.9 KiB

  1. using System;
  2. using System.Threading;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using Microsoft.Extensions.Options;
  5. using MongoDB.Driver;
  6. namespace DotNetCore.CAP.MongoDB.Test
  7. {
  8. public abstract class DatabaseTestHost : IDisposable
  9. {
  10. private string _connectionString;
  11. protected IServiceProvider Provider { get; private set; }
  12. protected IMongoClient MongoClient => Provider.GetService<IMongoClient>();
  13. protected IMongoDatabase Database => MongoClient.GetDatabase(MongoDBOptions.Value.DatabaseName);
  14. protected CapOptions CapOptions => Provider.GetService<IOptions<CapOptions>>().Value;
  15. protected IOptions<MongoDBOptions> MongoDBOptions => Provider.GetService<IOptions<MongoDBOptions>>();
  16. protected DatabaseTestHost()
  17. {
  18. CreateServiceCollection();
  19. CreateDatabase();
  20. }
  21. private void CreateDatabase()
  22. {
  23. Provider.GetService<MongoDBStorage>().InitializeAsync(CancellationToken.None).GetAwaiter().GetResult();
  24. }
  25. protected virtual void AddService(ServiceCollection serviceCollection)
  26. {
  27. }
  28. private void CreateServiceCollection()
  29. {
  30. var services = new ServiceCollection();
  31. services.AddOptions();
  32. services.AddLogging();
  33. _connectionString = ConnectionUtil.ConnectionString;
  34. services.AddOptions<CapOptions>();
  35. services.Configure<MongoDBOptions>(x => x.DatabaseConnection = _connectionString);
  36. services.AddSingleton<IMongoClient>(x => new MongoClient(_connectionString));
  37. services.AddSingleton<MongoDBStorage>();
  38. AddService(services);
  39. Provider = services.BuildServiceProvider();
  40. }
  41. public void Dispose()
  42. {
  43. MongoClient.DropDatabase(MongoDBOptions.Value.DatabaseName);
  44. }
  45. }
  46. }