MongoDB动态注册类类型

时间:2015-01-09 10:25:41

标签: mongodb c#-4.0

MongoDB中的

我需要动态注册类映射,我不需要自己注册所有当前和未来的类。

有一种名为

的方法
BsonClassMap.RegisterClassMap<T> 

但有了这个,我需要知道Class(T),而不能使用Type。

我想迭代这样的程序集类型来注册类映射:

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

有办法吗?

1 个答案:

答案 0 :(得分:6)

我终于找到了解决这个问题的方法。适用于遇到同样问题的其他人。

我检查了mongodb-c#-driver-source,以确定是否有其他方法可以动态注册类型。

方法

BsonClassMap.LookupClassMap(type);

将检查提供的类型是否已经注册。如果没有,它会注册它并调用AutoMap()。

为了确保该类未在其他地方注册,您应该像这样使用它:

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);
相关问题