How do I use BsonClassMap.RegisterClassMap to register classes from a referenced assembly

780 views
Skip to first unread message

richar...@gmail.com

unread,
Apr 22, 2013, 12:18:43 PM4/22/13
to mongod...@googlegroups.com
I've tried this;

var assemblyList = AppDomain.CurrentDomain.GetAssemblies();

foreach (var assembly in assemblyList)
{
     if (assembly.FullName.Contains("Assembly.Name"))
     {

          foreach (Type type in assembly.GetTypes())
          {
               BsonClassMap.RegisterClassMap<type>();
          }
     }
}

Unfortunately the variable type is of type Type and RegisterClassMap requires a Class

How do I register all classes from the assembly?

Tobias Koller

unread,
Jan 9, 2015, 5:13:43 AM1/9/15
to mongod...@googlegroups.com
hi,

I had the same problem and checked the c#-driver-source to find out if there is a solution for that.
There is a Method called BsonClassMap.LookupClassMap(type); which checks if the map Classtype is registered already.
If not it will automatically register the type and calls AutoMap(), too.

for example you could do something like this:
            var assemblyTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.IsClass);
            foreach (var type in assemblyTypes)
            {
                if (BsonClassMap.IsClassMapRegistered(type))
                    return;

                 //will check if the type is registered. if not it will automatically registered.
                 //AutoMap will also called automatically.
                 var map = BsonClassMap.LookupClassMap(type);
                 ....
Reply all
Reply to author
Forward
0 new messages