Skip to content

Instantly share code, notes, and snippets.

@par4dise
Forked from andreabalducci/BsonClassMapHelper.cs
Last active February 5, 2020 14:12
Show Gist options
  • Save par4dise/590477ececefe86016be1dc9fefbfbbf to your computer and use it in GitHub Desktop.
Save par4dise/590477ececefe86016be1dc9fefbfbbf to your computer and use it in GitHub Desktop.
Reset class map for unit testing
using System;
using System.Collections.Generic;
using System.Reflection;
using MongoDB.Bson.Serialization;
namespace Mongo.Gist
{
/// <summary>
/// Class BsonClassMapHelper.
/// </summary>
public static class BsonClassMapHelper
{
/// <summary>
/// Unregister a type.
/// </summary>
/// <typeparam name="T">Type to unregister.</typeparam>
public static void Unregister<T>()
{
var classType = typeof(T);
GetClassMap(classType).Remove(classType);
}
/// <summary>
/// Gets the mapping dictionary.
/// </summary>
/// <param name="classType"></param>
/// <returns></returns>
private static Dictionary<Type, BsonClassMap> GetClassMap(Type classType)
{
var classMap = BsonClassMap.LookupClassMap(classType);
var fieldInfo = typeof(BsonClassMap).GetField("__classMaps", BindingFlags.Static | BindingFlags.NonPublic);
return (Dictionary<Type, BsonClassMap>)fieldInfo.GetValue(classMap);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment