-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicLoad.cs
More file actions
70 lines (61 loc) · 3.1 KB
/
Copy pathDynamicLoad.cs
File metadata and controls
70 lines (61 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System.Reflection;
namespace DynamicLoad
{
public class DynamicLoad
{
public static T Assembly_Load_method<T>(string path)
{
if (File.Exists(path))
{
//Obtiene los ensamblados cargados dentro del dominio de aplicacion del hilo actual
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
//obtener el ensamblado de la biblioteca cargada y agrega al dominio de aplicacion del hilo actual
Assembly assemblyToLoad = Assembly.LoadFrom(Path.GetFullPath(path));
AppDomain.CurrentDomain.Load(assemblyToLoad.GetName());
List<Type> typesExported = assemblyToLoad.GetExportedTypes().ToList();
if (!typesExported.Any(eleTypes => eleTypes.GetTypeInfo().GetInterfaces().ToList().Any(eleInter => eleInter.FullName.Equals(typeof(T).FullName))))
{
throw new Exception($"no se encontro implementacion de la interfas '{typeof(T).FullName}', en el ensamblado {path}");
}
string typeFullName = typesExported.Find(eleTypes => eleTypes.GetTypeInfo().GetInterfaces().ToList().Any(eleInter => eleInter.FullName.Equals(typeof(T).FullName))).FullName;
LoadReferencedAssemblies(assemblyToLoad);
// Retorna una nueva instancia de <T> dado su nombre
return (T)Activator.CreateInstance(assemblyToLoad.GetType(typeFullName));
}
throw new FileNotFoundException(path);
}
private static void LoadReferencedAssemblies(Assembly assemblyToLoad)
{
AssemblyName[] referencedAssemblies = assemblyToLoad.GetReferencedAssemblies();
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (AssemblyName currentAssemblyName in referencedAssemblies)
{
var loadedAssembly = loadedAssemblies.FirstOrDefault(loadedAssembly => loadedAssembly.FullName == currentAssemblyName.FullName);
if (loadedAssembly == null)
{
Assembly referencedAssembly = null;
try
{
//First try to load using the assembly name just in case its a system dll
referencedAssembly = Assembly.Load(currentAssemblyName);
}
catch (FileNotFoundException ex)
{
try
{
referencedAssembly = Assembly.LoadFrom(Path.Join(Path.GetDirectoryName(assemblyToLoad.Location), currentAssemblyName.Name + ".dll"));
}
catch (Exception)
{
}
}
if (referencedAssembly != null)
{
LoadReferencedAssemblies(referencedAssembly);
AppDomain.CurrentDomain.Load(referencedAssembly.GetName());
}
}
}
}
}
}