您最多选择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. }