Skip to content

Commit

Permalink
Add bson class map by type
Browse files Browse the repository at this point in the history
  • Loading branch information
glucaci committed Jul 10, 2024
1 parent a60c5cd commit 0db6a38
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Context.Tests/MongoCollectionBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,22 @@ public void AddBsonClassMap_AddNewBsonClassMapWithoutParameter_BsonClassMapIsReg
Assert.True(BsonClassMap.IsClassMapRegistered(typeof(ItemWithoutSpecificClassMap)));
}

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

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

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

private class ItemClassMapNotRegistered
{
public int Id { get; set; }
Expand Down
4 changes: 4 additions & 0 deletions src/Context/IMongoCollectionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ IMongoCollectionBuilder<TDocument> AddBsonClassMap<TMapDocument>(
Action<BsonClassMap<TMapDocument>> bsonClassMapAction)
where TMapDocument : class;

IMongoCollectionBuilder<TDocument> AddBsonClassMap(
Type type,
Action<BsonClassMap>? bsonClassMapAction = default);

IMongoCollectionBuilder<TDocument> WithCollectionSettings(
Action<MongoCollectionSettings> collectionSettings);

Expand Down
25 changes: 25 additions & 0 deletions src/Context/Internal/MongoCollectionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ public IMongoCollectionBuilder<TDocument> AddBsonClassMap<TMapDocument>()
return this;
}

public IMongoCollectionBuilder<TDocument> AddBsonClassMap(
Type type,
Action<BsonClassMap>? bsonClassMapAction = default)
{
_classMapActions.Add(() =>
RegisterClassMapSync(type, bsonClassMapAction));

return this;
}

public IMongoCollectionBuilder<TDocument> WithCollectionSettings(
Action<MongoCollectionSettings> collectionSettings)
{
Expand Down Expand Up @@ -103,6 +113,21 @@ private void RegisterClassMapSync<TMapDocument>(
}
}

private void RegisterClassMapSync(
Type type,
Action<BsonClassMap>? bsonClassMapAction)
{
lock (_lockObject)
{
if (!BsonClassMap.IsClassMapRegistered(type))
{
var classMap = new BsonClassMap(type);
bsonClassMapAction?.Invoke(classMap);
BsonClassMap.RegisterClassMap(classMap);
}
}
}

private void RegisterClassMapSync<TMapDocument>()
where TMapDocument : class
{
Expand Down

0 comments on commit 0db6a38

Please sign in to comment.