Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB dynamically register class-types

Tags:

mongodb

c#-4.0

in MongoDB I need to register class-maps dynamically that I don't need to register all the current and future-classes myself.

There is a Method called

BsonClassMap.RegisterClassMap<T> 

but with this I need to know the Class (T) and can't use a Type instead.

I want to iterate through the assembly-types like this to register the class-maps:

var assemblyTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => t.IsClass);
        foreach (var type in assemblyTypes)
        {
            //Register classmap for type
        }

Is there a way to do that?

like image 334
Tobias Koller Avatar asked Jan 01 '26 21:01

Tobias Koller


1 Answers

I finally found a solution for this problem. Just for everyone else who has the same problem.

I checked the mongodb-c#-driver-source to find out if there is another method to register the types dynamically.

The method

BsonClassMap.LookupClassMap(type);

will check if the provided type is registered already. If not it will register it and calls AutoMap(), too.

And to make sure that the class is not registered somewhere else you should use it like this:

if (BsonClassMap.IsClassMapRegistered(type))
  return;

//will check if the type is registered. if not it will be automatically registered.
//AutoMap will also called automatically.
BsonClassMap.LookupClassMap(type);
like image 94
Tobias Koller Avatar answered Jan 04 '26 22:01

Tobias Koller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!