Resolving an assembly at runtime

I want to load assemblies dynamically in my app with an event AssemblyResolver

, but I don't understand how.

I saw this tutorial and tried it myself. At the end of 3 he wrote:

static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}
static void Print()
{
    var mainClass = new MainClass();
    mainClass.Print();
}

static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
    return Assembly.LoadFile(@"path to the library");
}

      

Actually I don't understand how this code is supposed to compile at all ... new MainClass()

cannot be compiled as unknown (type not loaded yet), loading happens at runtime.
If MainClass

was a known type, it shouldn't be allowed at all ...

How is this code supposed to work?

+3


source to share


2 answers


If you want to load an assembly that you don't know the content about (and then use reflection to instantiate your classes), you can simply use Assembly.Load()

if you have a fully qualified name (name, version, culture and public key token if present), or Assembly.LoadFrom

if you have his way.



AssemblyResolve

used to "redirect" the loading of an assembly that is "known" at compile time but must be loaded from a specific path at run time. You can clearly use it to "decorate and switch" an assembly (at compile time you have an assembly, at run time you load another assembly that implements the same classes).

0


source


If compiled because presumably you have a reference to a library with a type MainClass

and Print

even if it is an empty stub without any real implementation - or just the wrong implementation. It is not "unknown". If it were not known, then indeed this code would not compile, and you would have to use reflection to find the type at runtime, and reflection to instantiate an instance and reflection to invoke the method Print()

(unless a known interface or base class exists. which you can use, or are using dynamic

).

That's all you need to compile: metadata. In fact, it is relatively common for targeted "reference libraries", which are just that - this is how many multitagging features in your IDE work.



At runtime, you can override the load to provide the intended library, but honestly, it's usually easier to just deploy the actual library in the probe path (s) of your application (usually: next to the main exe). Also, your method ResolveAssembly

had it would be a good idea to check which assembly is being requested - it might be trying to load something completely unrelated, in which case just leave it alone.

0


source







All Articles