Skip to content

Commit 2cec865

Browse files
committed
Simplify entitymapper building
1 parent 80d2f23 commit 2cec865

File tree

1 file changed

+15
-21
lines changed

1 file changed

+15
-21
lines changed

LiteDB/Client/Mapper/BsonMapper.GetEntityMapper.cs

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -25,34 +25,28 @@ internal EntityMapper GetEntityMapper(Type type)
2525
}
2626

2727
using var cts = new CancellationTokenSource();
28-
mapper = new EntityMapper(type, cts.Token);
29-
if (_entities.TryAdd(type, mapper))
28+
try
3029
{
31-
try
30+
// We need to add the empty shell, because ``BuildEntityMapper`` may use this method recursively
31+
mapper = new EntityMapper(type, cts.Token);
32+
EntityMapper addedMapper = _entities.GetOrAdd(type, mapper);
33+
if (ReferenceEquals(addedMapper, mapper))
3234
{
33-
this.BuildEntityMapper(mapper);
34-
}
35-
catch (Exception e)
36-
{
37-
if (_entities.TryRemove(type, out var existingMapper))
35+
try
3836
{
39-
var isSameMapper = ReferenceEquals(mapper, existingMapper);
40-
if (!isSameMapper)
41-
{
42-
// Should never happen, but if it does, we need to put the existing mapper back in the cache
43-
_entities.TryAdd(type, existingMapper);
44-
}
37+
this.BuildEntityMapper(mapper);
38+
}
39+
catch (Exception ex)
40+
{
41+
_entities.TryRemove(type, out _);
42+
throw new LiteException(LiteException.MAPPING_ERROR, $"Error in '{type.Name}' mapping: {ex.Message}", ex);
4543
}
46-
47-
throw new LiteException(LiteException.MAPPING_ERROR, $"Error in '{type.Name}' mapping: {e.Message}", e);
4844
}
4945
}
50-
else
46+
finally
5147
{
52-
if (!_entities.TryGetValue(type, out mapper))
53-
{
54-
throw new LiteException(LiteException.MAPPER_NOT_FOUND, $"EntityMapper for type {type} was not found.");
55-
}
48+
// Allow the Mapper to be used for de-/serialization
49+
cts.Cancel();
5650
}
5751

5852
return mapper;

0 commit comments

Comments
 (0)