I\'m making a console app on .Net Core platform and was wondering, how does one load assemblies (.dll files) and instantiate classes using C# dynamic features? It seems so m
I think this below will work for you, and hope this can help some MEF2 newbie like me.
/// <summary>
/// Gets the assemblies that belong to the application .exe subfolder.
/// </summary>
/// <returns>A list of assemblies.</returns>
private static IEnumerable<Assembly> GetAssemblies()
{
string executableLocation = AppContext.BaseDirectory;
string directoryToSearch = Path.Combine(Path.GetDirectoryName(executableLocation), "Plugins");
foreach (string file in Directory.EnumerateFiles(directoryToSearch, "*.dll"))
{
Assembly assembly = null;
try
{
//Load assembly using byte array
byte[] rawAssembly = File.ReadAllBytes(file);
assembly = Assembly.Load(rawAssembly);
}
catch (Exception)
{
}
if (assembly != null)
{
yield return assembly;
}
}
}
another one, but in .netstandard1.3, neither was available.
var assembiles = Directory.GetFiles(Assembly.GetEntryAssembly().Location, "*.dll", SearchOption.TopDirectoryOnly)
.Select(AssemblyLoadContext.Default.LoadFromAssemblyPath);
Using .net core 1.1 / standard 1.6, I found that AssemblyLoader was not available, and
AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath)gave me a "Could not load file or assembly xxx" error.
Finally this solution below worked for me - purely by adding a step to get the AssemblyName object. Hope it helps anyone who gets stuck:
var assemblyName = AssemblyLoadContext.GetAssemblyName(assemblyPath); var assembly = Assembly.Load(assemblyName);