La classe Assembly prevede il metodo GetReferencedAssembly() per recuperare l’elenco degli AssemblyName ralativi agli assembly referenziati da un determinato assembly.
The problem is that if we have a structure with more dll referenced in the chain, the method returns only the first level of the same chain.
Suppose we have the following structure:
or the project AssemblyExtension reference the dll AssemblyExtensionLIB1 which, in turn, reference the AssemblyExtensionLIB2.
In this case, the method GetReferencedAssembly (), applied to an assembly AssemblyExtension, returns the following list:
As you can see there is no trace of AssemblyExtensionLIB2. The following method
di estensione provvede ad eseguire un algoritmo ricorsivo per recuperare una lista di AssemblyName contenente tutte le reference dell’assembly:
- Imports System.Runtime.CompilerServices
- Imports System.Reflection
-
- Module AssemblyExtension
-
- < Extension ()> _
- Public Sub GetAllReferenceAssemblies( ByVal sourceAssembly As Assembly ,
- ByVal allowGacAssembly As Boolean ,
- ByVal list As ICollection ( Of AssemblyName ))
- If sourceAssembly Is Nothing Then Throw New ArgumentNullException ( "Source Assembly" )
- If list Is Nothing Then Throw New ArgumentNullException ( "Destination List" )
- list.Add(sourceAssembly.GetName())
- If allowGacAssembly OrElse Not sourceAssembly.GlobalAssemblyCache Then
- Dim assemblies = sourceAssembly.GetReferencedAssemblies()
- For Each assemblyName In assemblies
- Dim query = From a In list _
- Where a.FullName = assemblyName.FullName _
- Select a
- If query.Count = 0 Then
- Dim assembly As Assembly = assembly.Load(assemblyName.FullName)
- assembly.GetAllReferenceAssemblies(allowGacAssembly, list)
- End If Next
- End If End
- Sub End Module
The extension method is applicable on any assemble and the parameters are:
- allowGacAssembly: indicates whether to search the references in DLLs contained in the GAC;
- list: the list that will contain AssemblyName search result.
If your project before writing:
- Dim list = New List (Of AssemblyName )
- Assembly. GetEntryAssembly (). GetAllReferenceAssemblies ( True , list)
We get:
allowGacAssembly While if we set = false:
Attenzione: il metodo GetReferencedAssembly restituisce gli assembly effettivamente referenziati (cioè quelli per i quali c’è almeno un tipo utilizzato) e non quelli inseriti nelle referenze di Visual Studio.
 
0 comments:
Post a Comment