lundi 5 février 2018

Registering DLL in another folder

I have a small console application which backs up and then copies new DLLs to an installation folder, and then is supposed to re-register the new DLLs. It can also restore DLLs from a backup and then re-register the backups.

I have the following code to perform the registeration:

Assembly asm = Assembly.LoadFrom(Path.Combine(Path.GetFullPath(options.RemotePath), Path.GetFileName(file)));
RegistrationServices regAsm = new RegistrationServices();
bool bResult = regAsm.RegisterAssembly(asm, AssemblyRegistrationFlags.SetCodeBase);

I'm having a problem with registering where on calling Assembly.LoadFrom I get a System.IO.FileLoadException with the message A procedure imported by 'MyLib.dll' could not be loaded

I thought this was probably a DLL in the remote folder that it was unable to load, so I wrapped my registration code in a change of current directory:

var wd = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(options.RemotePath);
...
Directory.SetCurrentDirectory(wd);

Unfortunately this didn't seem to resolve the issue. I did some more investigating and found that I can tell the AppDomain how to resolve dependencies using AppDomain.CurrentDomain.AssemblyResolve and ResolveEventHandler, and so I set this up by adding this code at the beginning of Main, before my registration code.

var otherCompanyDlls = new DirectoryInfo(options.RemotePath).GetFiles("*.dll");

Console.WriteLine("Setting AssemblyResolve");
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler((sender, a) =>
{
    Console.WriteLine("Looking for {0}", a.Name);
    var dll = otherCompanyDlls.FirstOrDefault(fi => fi.Name == a.Name);
    if (dll == null)
    {
        return null;
    }

    return Assembly.LoadFrom(dll.FullName);
});

I still get the same error, and this AssemblyResolve handler code never seems to be triggered since the Console line I added is never written.

What is it that I am doing wrong? I was hoping to at least find out what DLL dependency it was trying to load but I can't even seem to find that.





Aucun commentaire:

Enregistrer un commentaire