I am trying to serialize the configuration object of Nhibernate. When doing so I get the following error:
Unhandled exception. System.Runtime.Serialization.SerializationException: Type 'System.Type' in Assembly 'System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' is not marked as serializable.
at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(Type type)
at System.Runtime.Serialization.FormatterServices.<>c.<GetSerializableMembers>b__5_0(MemberHolder mh)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Type objectType, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, SerializationBinder binder)
I found that the root cause of this error is that there is a mapping in the configuration which maps a model using class Mapping. If I don't do any mapping in the configuration the serialization is done without any errors.
The issue you're encountering is related to the fact that the System.Type class is not marked as serializable. NHibernate's Configuration object, which contains mappings and various configurations, includes references to System.Type objects. When you attempt to serialize the Configuration, the serialization process fails because System.Type is not serializable.
At the beginning of the application, you don't have any mappers inside the configuration, so there is no problem in the serialization process. However, if you add mappers inside the configuration, it starts to create PersistentClass instances. A PersistentClass contains a member that is a Type class instance, but you can't serialize Type class instances. That is the real reason why JSON serialization fails in your scenario. Could you please try using binary serialization instead?