using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Entities; namespace PrivaPub.Infrastructure.Data { public interface IOwnId { string NewId(); } public static class EntityIds { static readonly Lock Gate = new(); public static void Register() { lock (Gate) { if (BsonClassMap.IsClassMapRegistered(typeof(Entity))) { if (BsonClassMap.LookupClassMap(typeof(Entity)).IdMemberMap?.IdGenerator is Generator) return; throw new InvalidOperationException( "The BSON map of Entity was built before EntityIds.Register(), so IDs would not be stored as they always were. Register them before anything touches a stored record."); } BsonClassMap.RegisterClassMap(map => { map.AutoMap(); map.SetIgnoreExtraElements(true); var id = map.MapIdProperty(entity => entity.ID); ((IBsonMemberMapAttribute)new AsObjectIdAttribute()).Apply(id); id.SetIdGenerator(new Generator()); }); } } sealed class Generator : IIdGenerator { public object GenerateId(object container, object document) => document is IOwnId own ? own.NewId() : ObjectId.GenerateNewId().ToString(); public bool IsEmpty(object id) => string.IsNullOrEmpty(id as string); } } }