MongoDB C#驱动程序-序列化集合到接口

时间:2018-10-17 22:25:36

标签: c# mongodb interface mongodb-.net-driver event-sourcing

由于工作环境的限制,我在MongoDB中实现了一个粗糙的Event Sourcing存储。我试图像这样从Mongo获取IClientEvents的列表:

 var events = await _db.GetCollection<IClientEvent>("ClientEvents").FindAsync(c => c.ClientId == clientId);

运行上述存储库方法时,出现以下异常:

Message: System.InvalidOperationException : {document}.ClientId is not supported.

IClientEvent接口定义为:

public interface IClientEvent
{
    Guid Id { get; set; }
    long TimeStamp { get; set; }
    Guid ClientId { get; set; }
}

public class ClientChangedEvent : IClientEvent
{
    public Guid Id { get; set; }
    public long TimeStamp { get; set; }
    public Guid ClientId { get; set; }

    public IEnumerable<Change> Changes;
    // ... other properties for the event
}

单个集合中将存储许多不同的事件类型,所有事件类型都将实现IClientEvent。我只想通过一个电话获得clientId对客户端发生的所有事件。

我已经注册了IClientEvent的所有具体实现,甚至添加了自定义标识符:

        var clientEventsDiscriminator = new ClientEventsMongoDiscriminatorConvention();
        BsonSerializer.RegisterDiscriminatorConvention(typeof(IClientEvent),clientEventsDiscriminator);
        BsonClassMap.RegisterClassMap<ClientChangedEvent>();
        BsonSerializer.RegisterDiscriminatorConvention(typeof(ClientChangedEvent), clientEventsDiscriminator);

我什至尝试注册this SO post中提到的ImpliedImplementationInterfaceSerializer,但是当我注册第二个具体实现时,它已经为IClientEvent注册了序列化程序,这会引发异常。

不确定从这里要去哪里。任何帮助将不胜感激!

-编辑更多代码:

这是完整的注册码:

        var clientEventsDiscriminator = new ClientEventsMongoDiscriminatorConvention();
        BsonSerializer.RegisterDiscriminatorConvention(typeof(IClientEvent),clientEventsDiscriminator);

        clientEventsDiscriminator.AddEventType<ClientChangedEvent>();
        BsonClassMap.RegisterClassMap<ClientChangedEvent>();
        BsonSerializer.RegisterDiscriminatorConvention(typeof(ClientChangedEvent), clientEventsDiscriminator);

        clientEventsDiscriminator.AddEventType<ClientAddedEvent>();
        BsonClassMap.RegisterClassMap<ClientAddedEvent>();
        BsonSerializer.RegisterDiscriminatorConvention(typeof(ClientAddedEvent), clientEventsDiscriminator);

这是鉴别器:

    public class ClientEventsMongoDiscriminatorConvention : IDiscriminatorConvention
{
    private Dictionary<string, Type> _eventTypes = new Dictionary<string, Type>();

    public string ElementName => "_eventType";

    public BsonValue GetDiscriminator(Type nominalType, Type actualType)
    {
        return GetDiscriminatorValueForEventType(actualType);
    }

    public Type GetActualType(IBsonReader bsonReader, Type nominalType)
    {
        var bookmark = bsonReader.GetBookmark();
        bsonReader.ReadStartDocument();
        if (!bsonReader.FindElement(ElementName))
        {
            throw new InvalidCastException($"Unable to find property '{ElementName}' in document. Cannot map to an EventType.");
        }

        var value = bsonReader.ReadString();
        bsonReader.ReturnToBookmark(bookmark);

        if (_eventTypes.TryGetValue(value, out var type))
        {
            return type;
        }

        throw new InvalidCastException($"The type '{value}' has not been registered with the '{nameof(ClientEventsMongoDiscriminatorConvention)}'.");
    }

    private string GetDiscriminatorValueForEventType(Type type)
    {
        var indexOfEventWord = type.Name.IndexOf("Event");
        if (indexOfEventWord == -1)
        {
            return type.Name;
        }
        return type.Name.Substring(0, indexOfEventWord);
    }

    public void AddEventType<T>()
    {
        var discriminatorName = GetDiscriminatorValueForEventType(typeof(T));
        _eventTypes.TryAdd(discriminatorName, typeof(T));
    }
}

在运行代码时,似乎从未命中鉴别器的GetActualType方法。

1 个答案:

答案 0 :(得分:0)

我通过简单地将IClientEvent从接口更改为抽象类而设法使其工作。