Created
February 6, 2014 15:13
-
-
Save tjchaplin/8846073 to your computer and use it in GitHub Desktop.
Mongodb - Add BsonType information based on Convention
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void RegisterBsonClassMappings() | |
{ | |
//AnyBaseClass is defined as a root | |
BsonClassMap.RegisterClassMap<AnyBaseClass>(cm => | |
{ | |
cm.AutoMap(); | |
cm.SetIsRootClass(true); | |
}); | |
//IAnyInterface is a marker interface which falls in the inheritence tree for | |
//AnyBaseClass | |
var type = typeof(IAnyInterface); | |
AppDomain.CurrentDomain.GetAssemblies() | |
.SelectMany(s => s.GetTypes()) | |
.Where(x => type.IsAssignableFrom(x) | |
&& x != typeof(AnyBaseClass) | |
&& x.IsClass) | |
.ForEach(BsonClassMapGeneric); | |
} | |
//Register the type so that mongodb can serialize type | |
private static void BsonClassMapGeneric(Type x) | |
{ | |
var method = typeof(BsonClassMap).GetMethod("RegisterClassMap", new Type[] { }); | |
var generic = method.MakeGenericMethod(x); | |
generic.Invoke(null, null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment