Skip to content

Commit

Permalink
Added AddBsonClassMap without parameters. (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
nscheibe authored Jan 13, 2020
1 parent b95486c commit f0c3925
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
23 changes: 22 additions & 1 deletion src/Context.Tests/MongoCollectionBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,33 @@ public void AddBsonClassMap_AddNewBsonClassMapSeveralTimes_BsonClassMapIsRegiste
// Assert
Assert.True(BsonClassMap.IsClassMapRegistered(typeof(Order)));
}


[Fact]
public void AddBsonClassMap_AddNewBsonClassMapWithoutParameter_BsonClassMapIsRegistered()
{
// Arrange
var mongoCollectionBuilder =
new MongoCollectionBuilder<ItemWithoutSpecificClassMap>(_mongoDatabase);

// Act
mongoCollectionBuilder.AddBsonClassMap<ItemWithoutSpecificClassMap>();
IMongoCollection<ItemWithoutSpecificClassMap> result = mongoCollectionBuilder.Build();

// Assert
Assert.NotNull(result);
Assert.True(BsonClassMap.IsClassMapRegistered(typeof(ItemWithoutSpecificClassMap)));
}

private class ItemClassMapNotRegistered
{
public int Id { get; set; }
}

private class ItemWithoutSpecificClassMap
{
public int Name { get; set; }
}

#endregion

#region WithMongoCollectionSettings Tests
Expand Down
24 changes: 23 additions & 1 deletion src/Context/Internal/MongoCollectionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,17 @@ public IMongoCollectionBuilder<TDocument> WithCollectionName(string collectionNa
public IMongoCollectionBuilder<TDocument> AddBsonClassMap<TMapDocument>(
Action<BsonClassMap<TMapDocument>> bsonClassMapAction) where TMapDocument : class
{
_classMapActions.Add(() => RegisterClassMapSync(bsonClassMapAction));
_classMapActions.Add(() =>
RegisterClassMapSync<TMapDocument>(bsonClassMapAction));

return this;
}

public IMongoCollectionBuilder<TDocument> AddBsonClassMap<TMapDocument>()
where TMapDocument : class
{
_classMapActions.Add(() =>
RegisterClassMapSync<TMapDocument>());

return this;
}
Expand Down Expand Up @@ -94,5 +104,17 @@ private void RegisterClassMapSync<TMapDocument>(
}
}
}

private void RegisterClassMapSync<TMapDocument>()
where TMapDocument : class
{
lock (_lockObject)
{
if (!BsonClassMap.IsClassMapRegistered(typeof(TMapDocument)))
{
BsonClassMap.RegisterClassMap<TMapDocument>();
}
}
}
}
}

0 comments on commit f0c3925

Please sign in to comment.