public MongoEventStore(ILoggerFactory loggerFactory, IEventStoreOptions options) { if (!(options is IMongoEventStoreOptions mongoOptions)) { throw new Exception("Options should be of type IMongoDatabaseOptions"); } Logger = loggerFactory.CreateLogger(GetType()); var mongoClientSettings = new MongoClientSettings { Server = MongoServerAddress.Parse(mongoOptions.ConnectionString) }; try { var client = new MongoClient(mongoClientSettings); var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"); if (string.IsNullOrWhiteSpace(environment)) { environment = "testing"; } var mongoDatabase = client.GetDatabase($"{mongoOptions.DatabaseName}-{environment}"); Collection = mongoDatabase.GetCollection <TEvent>(options.CollectionName); } catch (Exception exception) { Logger.LogCritical( $"Error while connecting to {mongoClientSettings.Server.Host}. Exception: {exception.Message}", exception); throw; } }
private static void AddEventStore <T>(this IServiceCollection services, IEventStoreOptions options) { services.AddMemoryCache(); services.AddLogging(); services.AddSingleton(options); switch (options) { case IMongoEventStoreOptions _: { BsonSerializer.RegisterSerializer(typeof(DateTime), DateTimeSerializer.LocalInstance); services.AddSingleton <IEventStore <T>, MongoEventStore <T> >(); break; } case IInMemoryEventStoreOptions _: { services.AddSingleton <IEventStore <T>, MongoEventStore <T> >(); break; } default: throw new ArgumentOutOfRangeException("Unsupported database"); } }