mercredi 2 septembre 2020

Can I run code from a newer .NET version in an older .NET version?

I have an application in .NET 4.6 and I need to instantiate some dataobject in a newer .NET version (using a NuGet package that's only available in .NET 4.7

I want to use a project structure something like the following:
Project structure

I have been messing around a little bit with manually copying and loading the Instantiator.dll files and it seems to work fine:

var fi = new FileInfo("Instantiator.dll");
var ass = Assembly.LoadFile(fi.FullName);
var instance = ass.CreateInstance("Instantiator.DataLoader");
if (instance == null) throw new Exception();
var type = instance.GetType();
var method = type.GetMethod("Load");
if (method == null) throw new Exception();
var result = (SomeData)method.Invoke(instance, null);

So my questions are:
Is this the right way to do something like this?
Is there some way to automatically build/copy Instantiator.csproj?
Are there any risks associated with my sample code?
Why does my sample code work at all? You'd think it's impossible considering the project reference block.





Aucun commentaire:

Enregistrer un commentaire