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
@Rob, the only way I could get your example to build was to change your "myInstance" type to dynamic.
Leaving the type as var does allow the code to build but as soon as I try and use a method from the runtime loaded assembly, I get compiler errors such as myInstance does not contain method X. I'm new at this but marking the type as dynamic, does seem to make sense. If the type is loaded at runtime then how can the compiler verify myInstance will contain method X or prop Y ? By typing the myInstance as dynamic I believe you are removing the compiler checking and thus I could get the example to build and run just fine. Not sure this is 100% the correct way ( I don't know enough and you may advise that there's an issue using dynamic?) but it is the only way I got it to work without having to go to the trouble of creating my own AssemblyLoader (as you correctly point out).
So...
using System;
using System.Runtime.Loader;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
var myAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(@"C:\Documents\Visual Studio 2017\Projects\Foo\Foo\bin\Debug\netcoreapp2.0\Foo.dll");
var myType = myAssembly.GetType("Foo.FooClass");
dynamic myInstance = Activator.CreateInstance(myType);
myInstance.UpperName("test");
}
}
}
Hope this helps someone as being new it took me ages to pinpoint why myInstance as a var didn't have method X etc Doh!