How to load assemblies located in a folder in .net core console app

前端 未结 8 1059
甜味超标
甜味超标 2020-11-28 07:06

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

相关标签:
8条回答
  • 2020-11-28 07:47

    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);
    
    0 讨论(0)
  • 2020-11-28 07:49

    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);
    0 讨论(0)
提交回复
热议问题