How can I dynamically reference an assembly that looks for another assembly?

谁说我不能喝 提交于 2019-12-04 05:25:17

If it can't find a dependent assembly in the usual places, you'll need to manually specify how to find them.

The two easiest ways I'm aware of for doing this:

  1. manually load the dependent assemblies in advance with Assembly.Load.

  2. handle the AssemblyResolve event for the domain which is loading the assembly with additional assembly dependencies.

Both essentially require you to know the dependencies for the assembly you're trying to load in advance but I don't think that's such a big ask.

If you go with the first option, it would also be worthwhile looking into the difference between a full Load and a reflection-only Load.

If you would rather go with 2 (which I'd recommend), you can try something like this which has the added benefit of working with nested dependency chains (eg MyLib.dll references LocalStorage.dll references Raven.Client.dll references NewtonSoft.Json.dll) and will additionally give you information about what dependencies it can't find:

AppDomain.CurrentDomain.AssemblyResolve += (sender,args) => {

    // Change this to wherever the additional dependencies are located    
    var dllPath = @"C:\Program Files\Vendor\Product\lib";

    var assemblyPath = Path.Combine(dllPath,args.Name.Split(',').First() + ".dll");

    if(!File.Exists(assemblyPath))
       throw new ReflectionTypeLoadException(new[] {args.GetType()},
           new[] {new FileNotFoundException(assemblyPath) });

    return Assembly.LoadFrom(assemblyPath);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!