How to load a DLL and runtime, invoke a method my name, get result object and use it as a parameter on another unkown DLL .NET Core

That post title took me a while to come up with, but my idea is pretty simple, what id you need sort of a bootstrap that don't reference DLLs, still be able to manage a simple operation of of invoking methods and pass results to the next DLL on the list. C# and .NET Core as a strong type based doesn't really have obvious ways to accomplish this, but i think i got to it with the following code, what do you think?




string sourceAsmName = "DllToLoadName";
Assembly sourceAsm = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppContext.BaseDirectory + sourceAsmName + @".dll");
AssemblyLoadHelper.LoadReferencedAssemblies(sourceAsm);

Type sourceType = sourceAsm.GetType(sourceAsmName + "." + source);
MethodInfo? sourceMethod = sourceType.GetMethod("extract");
object? sourceInstance = Activator.CreateInstance(sourceType, new object[] { _config, _logger });

Task sourceTask = (Task)sourceMethod.Invoke(sourceInstance, null);
_logger.LogInformation("start invoking source extract");
await sourceTask.ConfigureAwait(false);
object sourceObject = (object)((dynamic)sourceTask).Result;

public static class AssemblyLoadHelper
    {
        public static void LoadReferencedAssemblies(Assembly assembly)
        {
            AssemblyName[] refAsmsNames = assembly.GetReferencedAssemblies();
            List refAsms = new List();
            //First load all module referanced dlls
            foreach (AssemblyName refAsmName in refAsmsNames)
            {
                if (System.IO.File.Exists(AppContext.BaseDirectory + refAsmName.Name + @".dll"))
                {
                    Assembly refAsm = AssemblyLoadContext.Default.LoadFromAssemblyPath(AppContext.BaseDirectory + refAsmName.Name + @".dll");
                    if (!AppDomain.CurrentDomain.GetAssemblies().Contains(refAsm))
                    {
                        refAsms.Add(refAsm);
                    }
                }
                else
                {
                    try
                    {
                        AssemblyLoadContext.Default.LoadFromAssemblyName(refAsmName);
                    }
                    catch (Exception ex)
                    {

                    }

                }
            }
        }
    }

Popular posts from this blog

add extra files on deploy ASP Core web app using publish profile

how to copy NuGet packages from one project to another

S/MIME Certificate and GMail