VB.Net搜索命名空间的泛型类型(反射)

时间:2010-09-27 01:01:54

标签: .net vb.net entity-framework reflection

我正在尝试使用上下文动态注册实体和配置(仅限ef4代码)

我通常会这样做:

Private Shared Sub ConfigureDatabase(ByRef Builder As ContextBuilder(Of ContextExtension))
  'Load configurations for each of the tables (Entity sets) in our database...
  ConfigureEntity(Builder, New ContactConfig)
End Sub

 Private Shared Sub ConfigureEntity(Of T)(ByRef Builder As ContextBuilder(Of ContextExtension), ByVal config As EntityConfiguration(Of T), ByVal setName As String)
    'Register the entity configuration with the builder
    Builder.Configurations.Add(config)

    'Register the entity set name with the builder
    Builder.RegisterSet(Of T)(setName)
End Sub

其中ContactConfig是继承EntityConfiguration(Of Contact)的类,Contact是实现接口IEntity的类(IEntity对所有实体都是通用的)。

所以......我需要搜索一个命名空间(比如Project.DB.Client)来查找匹配的所有签名:

EntityConfiguration(Of <Class which implements IEntity>)

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

命名空间只是对象名称的一部分。搜索继承泛型类的类型比仅按命名空间名称过滤要多得多:

Private Function CheckType(ByVal type As Type) As Boolean
    If (type Is GetType(Object)) Then ' object hierarhy root reached'
        Return False
    End If
    If (type.IsGenericType) Then
        ' inherits from some generic type'
        Dim parameters = type.GetGenericArguments()
        ' check if it has generic 1 parameter'
        If parameters.Length = 1 Then
            ' check if generic parameter is defined'
            If Not (parameters(0).FullName Is Nothing) Then
                ' check if parameter implements IEntity'
                If GetType(IEntity).IsAssignableFrom(parameters(0)) Then
                    ' check if it is EntityConfiguration(Of T)'
                    If type Is GetType(EntityConfiguration(Of )).MakeGenericType(parameters) Then
                        Return True
                    End If
                End If
            End If
        End If
    End If
    Return CheckType(type.BaseType)
End Function

Function FilterTypes(ByVal nameSpaceName As String, ByVal types As IEnumerable(Of Type)) As List(Of Type)
    Dim result As New List(Of Type)
    ' append . to namespace name'
    nameSpaceName = nameSpaceName + "."
    For Each type As Type In types
        ' we do not need abstract classes, wont be able to create their instances anyway'
        If (type.IsClass And Not type.IsAbstract And
             type.FullName.StartsWith(nameSpaceName)) Then
            ' check if type is inherited from EntityConfiguration(Of T)'
            If (CheckType(type)) Then
                result.Add(type)
            End If
        End If
    Next
    Return result
End Function

CheckType函数检查类型是否继承自EntityConfiguration(Of T)

FilterTypes函数还按名称空间过滤类型,并返回过滤后的列表结果。

示例:Dim types = FilterTypes("Project.DB.Client", Assembly.GetExecutingAssembly().GetTypes())