1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . IO ;
4
+ using System . Linq ;
5
+ using System . Reflection ;
6
+ using System . Text . RegularExpressions ;
7
+ using KY . Core . DataAccess ;
8
+
9
+ namespace KY . Core
10
+ {
11
+ public static class NugetPackageDependencyLoader
12
+ {
13
+ public static void Activate ( )
14
+ {
15
+ AppDomain . CurrentDomain . AssemblyResolve += Resolve ;
16
+ }
17
+
18
+ public static void Deactivate ( )
19
+ {
20
+ AppDomain . CurrentDomain . AssemblyResolve -= Resolve ;
21
+ }
22
+
23
+ private static Assembly Resolve ( object sender , ResolveEventArgs args )
24
+ {
25
+ Assembly assembly = AppDomain . CurrentDomain . GetAssemblies ( ) . FirstOrDefault ( x => x . FullName == args . Name ) ;
26
+ if ( assembly != null )
27
+ {
28
+ return assembly ;
29
+ }
30
+ Regex regex = new Regex ( @"(?<name>[\w.]+),\sVersion=(?<version>[\d.]+),\sCulture=(?<culture>[\w-]+),\sPublicKeyToken=(?<token>\w+)" ) ;
31
+ Match match = regex . Match ( args . Name ) ;
32
+ if ( match . Success )
33
+ {
34
+ string name = match . Groups [ "name" ] . Value ;
35
+ if ( name . StartsWith ( "System." ) )
36
+ {
37
+ return null ;
38
+ }
39
+ List < DirectoryInfo > versions = FileSystem . GetDirectoryInfos ( FileSystem . Combine ( Environment . ExpandEnvironmentVariables ( "%USERPROFILE%" ) , ".nuget\\ packages" , name ) ) . ToList ( ) ;
40
+ FileSystem . GetDirectoryInfos ( FileSystem . Combine ( Environment . ExpandEnvironmentVariables ( "%PROGRAMFILES%" ) , "dotnet\\ sdk\\ NuGetFallbackFolder" , name ) ) . ForEach ( versions . Add ) ;
41
+ Version version = new Version ( match . Groups [ "version" ] . Value ) ;
42
+ DirectoryInfo versionDirectory = versions . FirstOrDefault ( x => x . Name == version . ToString ( ) )
43
+ ?? versions . FirstOrDefault ( x => x . Name . StartsWith ( version . ToString ( 3 ) ) )
44
+ ?? versions . FirstOrDefault ( x => x . Name . StartsWith ( version . ToString ( 2 ) ) )
45
+ ?? versions . FirstOrDefault ( x => x . Name . StartsWith ( version . ToString ( 1 ) ) ) ;
46
+ if ( versionDirectory != null )
47
+ {
48
+ string fullPath = FileSystem . Combine ( versionDirectory . FullName , "lib" , "netstandard2.0" , name ) + ".dll" ;
49
+ return Assembly . LoadFile ( fullPath ) ;
50
+ }
51
+ }
52
+ return null ;
53
+ }
54
+ }
55
+ }
0 commit comments