SSIS 脚本组件:FileNotFoundException:无法加载文件或程序集 'MongoDB.Driver

SSIS Script component: FileNotFoundException: Could not load file or assembly 'MongoDB.Driver

我正在使用脚本组件将数据更新到 MongoDB。由于 MongoDB 驱动程序未签名,因此无法添加到 GAC,我使用以下方法在 运行 时间从保存所有需要的参考 DLL 的已知位置加载它:

private const string AssembyPath = @"C:\Users\acme\source\repos\import-members-and-optins\lib";
    
static ScriptMain()

{
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    // retrieve just a name of this assembly
    var assemblyName = args.Name.Split(',')[0];
    string fullPath = Path.Combine(AssembyPath, string.Format("{0}.dll", assemblyName));
    try
    {
        return Assembly.LoadFile(fullPath);
    }
    catch (Exception ex)
    {
        throw new Exception($"{fullPath} not found", ex);
    }
}

但是,我遇到了以下异常,我什至无法对其进行调试,因为它发生在任务能够 运行 之前。就像从未执行过处理程序一样。我已经检查过,我的包在 x86 中是 运行ning,所以我应该能够调试它,但我的处理程序从未被命中。 :-(

Package Validation Error Error at Data Flow Task [Upsert Mongo [69]]: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'ScriptMain' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'MongoDB.Driver, Version=2.14.1.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. at ScriptMain..cctor()
--- End of inner exception stack trace --- at ScriptMain..ctor() --- End of inner exception stack trace --- at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)

我在这里缺少什么?

我认为主要问题是由 在 class 中全局启动变量 引起的,它在程序集解析器被触发之前被调用。

尽量不要在 public class ScriptMain : UserComponent class 中启动任何变量,并将它们移动到适当的方法或 PreExecute 方法中。

尝试将您的代码更改为以下内容:

static ScriptMain()

{
    AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string AssembyPath = @"C:\Users\acme\source\repos\import-members-and-optins\lib";
    // retrieve just a name of this assembly
    var assemblyName = args.Name.Split(',')[0];
    string fullPath = Path.Combine(AssembyPath, string.Format("{0}.dll", assemblyName));
    try
    {
        return Assembly.LoadFile(fullPath);
    }
    catch (Exception ex)
    {
        throw new Exception($"{fullPath} not found", ex);
    }
}

另外,确保没有全局启动其他变量。

有用的资源