繁体   English   中英

通过反射调用动态加载的DLL方法,但目标引用了一个DLL

[英]Calling a dynamically loaded DLL method through reflection, but the target references a DLL

我需要在也是我的一堆DLL中动态调用一个方法。 DLL的数量未知,它们可能处于不同的版本。 我动态加载每个DLL,并使用反射在其中调用静态方法。 基本上我的代码看起来像这样

foreach (var myThing in instances)
{
    try {
        Assembly a = Assembly.LoadFile(myThing.DllPath);
        Type t = a.GetType("MyNamespace.Services");
        MethodInfo m = t.GetMethod("Backup");
        bool b = (bool)m.Invoke(null, new object[] { "Autobackup"+date+".zip", "Bot" });
    } catch (Exception e){
        LogInternalExceptions(e); // recursively vomit e.InternalException into logs
    }
}

问题在于Backup方法位于引用另一个DLL(log4net)的静态类中。

public static class Services
{
    private static ILog Log = LogManager.GetLogger(typeof(Services));

    public static bool Backup(string filename, string comment)
    {
        // ... snip ...
        Log.Info("Aww right, Princess!");
        return true;
    }
}

因此,我得到了预期的错误Could not load file or assembly 'log4net, ...' or one of its dependencies. File not found. Could not load file or assembly 'log4net, ...' or one of its dependencies. File not found.

我确定这不是我唯一使用此方法的问题,但这是第一个问题,我很困惑。 我可以编辑调用者或目标代码,但我真的不知道如何。 目标是Asp.net MVC3应用程序,但是该类只是一个非常通用的通用服务类。

我想在目标中使用类似预处理程序的语句; 就像是

#if REFLECTION
Log.Info("Aww right, Princess!");
#endif

但是我知道那没有意义,因为还没有到那个阶段,我还能如何避免这个问题?

在调用者项目中添加log4net引用并不能真正解决问题。 这意味着,如果我有log4net以外的其他参考,它们仍然会引起问题。

Assembly.LoadFile无法解决依赖关系,这会导致您描述的异常。 使用LoadLoadFrom应该可以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM