Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

55 righe
1.8 KiB

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