void IMongoDbCollectionContext.Initialize(string collectionName, MongoDbContext dbContext, CancellationToken cancellationToken) { CollectionName = collectionName ?? throw new ArgumentNullException(nameof(collectionName)); bool needSetup = false; var collectionNames = dbContext.Database.ListCollectionNames(cancellationToken: cancellationToken).ToList(cancellationToken); if (!collectionNames.Any(it => it.ToLower() == CollectionName.ToLower())) { dbContext.Database.CreateCollection(CollectionName, GetCreationOptions(), cancellationToken); needSetup = true; } var collectionSettings = GetCollectionSettings(); if (collectionSettings == null) { collectionSettings = new MongoCollectionSettings(); } Collection = dbContext.Database.GetCollection <TDocument>(CollectionName, collectionSettings); if (needSetup) { OnSetupCollection(cancellationToken); } }