How to make an external assembly available at runt

2019-08-26 09:34发布

问题:

I asked a question here and apparently the problem is where I can load an assembly using Reflection's Assembly.LoadFile or Assembly.LoadFrom, and get the type inside that assembly, the assembly is still not accessible in the whole application. So when WPF tries to resolve a type, it doesn't find that type because it doesn't find the assembly.

My question is, can I reference an assembly at runtime, so that it will be resolvable by WPF?

回答1:

A solution that works for me is handling the CurrentDomain.AssemblyResolve event

AppDomain.CurrentDomain.AssemblyResolve += 
    new ResolveEventHandler(OnAssemblyResolveFailure);

Assembly OnAssemblyResolveFailure(object sender, ResolveEventArgs args)
    {
        AssemblyName name = new AssemblyName(args.Name);
        Assembly assembly = .. //some logic here to load the assembly from assembly name
        return assembly;
    }

This way if the application cannot resolve an assembly name it will call your handler to find it