The 2.19.1 driver update is causing havoc on my project

After updating to 2.19.1 I’m getting the “is not configured as a type that is allowed to be serialized for this instance of ObjectSerializer” error on a bunch of my classes.

I registered this serializer to ok any and all types. It cleared up a bunch of errors.

               Func<Type, bool> serializer = delegate (Type type)
                {
                    return true;
                };

                var objectSerializer = new ObjectSerializer(serializer);
                BsonSerializer.RegisterSerializer(objectSerializer);

But I’m still getting errors when using this line of code. When WidgetData is an “object” type. I tried feeding the objectSerializer into ToBsonDocument(). But that didn’t help.
WidgetData.ToBsonDocument()

Hi, @Donny_V,

Welcome to the MongoDB Community Forums. I understand that you’re running into a situation where the ObjectSerializer is failing to serialize WidgetData. This can happen if your custom ObjectSerializer registration is not early enough in your bootstrap process and the default ObjectSerializer is registered first.

The following is a simple console program that serializes an empty WidgetData successfully after first registering a custom ObjectSerializer. This succeeds. If you comment out the custom ObjectSerializer registration, it will fail with the error that you noted. This suggests that the root cause of the problem is not registering your custom ObjectSerializer early enough.

using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;

var objectSerializer = new ObjectSerializer(x => true);
BsonSerializer.RegisterSerializer(objectSerializer);

object obj = new WidgetData();
var bson = obj.ToBsonDocument();
Console.WriteLine(bson);

record WidgetData;

Another way to avoid this problem is to use the ToBsonDocument(Type type) overload as that uses the BsonClassMapSerializer<T> rather than the ObjectSerializer to serialize the POCO to BSON.

using System;
using MongoDB.Bson;

object obj = new WidgetData();
var bson = obj.ToBsonDocument(obj.GetType());
Console.WriteLine(bson);

record WidgetData;

Hopefully this assists you in resolving the issue.

Sincerely,
James

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.