简体   繁体   English

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

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

I need to dynamically call a method in a bunch of DLLs that are also mine. 我需要在也是我的一堆DLL中动态调用一个方法。 There is an unknown amount of DLLs to call and they might be in different versions. DLL的数量未知,它们可能处于不同的版本。 I dynamically load each DLL and invoke a static method within them using reflection. 我动态加载每个DLL,并使用反射在其中调用静态方法。 Basically my code looks like this 基本上我的代码看起来像这样

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
    }
}

The problem is that the Backup method lives in a static class that references another DLL (log4net). 问题在于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;
    }
}

So, I get the expected error 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. Could not load file or assembly 'log4net, ...' or one of its dependencies. File not found. .

I'm sure that this is not my only issue with this method, but it's the first one and I'm stumped. 我确定这不是我唯一使用此方法的问题,但这是第一个问题,我很困惑。 I can edit the caller or the target code, but I don't really know how. 我可以编辑调用者或目标代码,但我真的不知道如何。 The target is an Asp.net MVC3 application, but the class is just a pretty generic general purpose service class. 目标是Asp.net MVC3应用程序,但是该类只是一个非常通用的通用服务类。

I would wnat to use something like a preprocessor statement in the target; 我想在目标中使用类似预处理程序的语句; something like 就像是

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

But I know that makes no sense, because it's not in that stage, how else could I avoid this issue? 但是我知道那没有意义,因为还没有到那个阶段,我还能如何避免这个问题?

Adding log4net reference to the caller project doesn't really solve the big picture. 在调用者项目中添加log4net引用并不能真正解决问题。 Meaning that if I have some references other than log4net, they would still causes an issue. 这意味着,如果我有log4net以外的其他参考,它们仍然会引起问题。

Assembly.LoadFile does not resolve dependencies which leads to the exception you describe. Assembly.LoadFile无法解决依赖关系,这会导致您描述的异常。 Using Load or LoadFrom should resolve your issue. 使用LoadLoadFrom应该可以解决您的问题。

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

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