无法使用 COM 加载文件或程序集“Microsoft.Extensions.DependencyInjection.Abstractions”

Posted

技术标签:

【中文标题】无法使用 COM 加载文件或程序集“Microsoft.Extensions.DependencyInjection.Abstractions”【英文标题】:Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions using COM 【发布时间】:2020-05-29 17:07:16 【问题描述】:

[最近的笔记]

如果不是因为共同可见方面,这个问题将与this question on assembly binding 重复。我挣扎了好几天,因为我没有意识到我需要改变我的单元测试项目以及 com 可见项目。如果您不想阅读我在实现这一点时遇到的困难,请跳到最后一次更新。

[序言]

我担心它可能是一个桥梁,试图通过 COM Visible Framework 4.7.2 库从 VB6 访问 dotnet 标准 2.0 库,但我想尝试一下。

Hello World 确实有效。 (即调用一个返回字符串的简单函数)

但是,当我尝试通过 IDE 或作为 .EXE 运行 VB6 程序时出现此错误。

错误信息表示c# dotnet standard2.0库的代码出现问题。

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, 
Version=3.1.0.0, Culture=neutral, 
PublicKeyToken=adb9793829ddae60' or one of its dependencies. 
The system cannot find the file specified.
File name: 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0,
Culture=neutral, PublicKeyToken=adb9793829ddae60'
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.<GetOrAdd>g__BuildServiceProvider|3()
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.<GetOrAdd>b__2(Int64 k)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, Boolean providerRequired)
at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options)
at SBDSTD.Standard.Entities.ApiDbContext..ctor(DbContextOptions options)
at SBDSTD.Standard.Services.Helper.MakeContext(String connectionString)

发生错误的库代码是

public static ApiDbContext MakeContext(string connectionString)

       var optionsBuilder = new DbContextOptionsBuilder<ApiDbContext>();
       optionsBuilder.UseSqlServer(connectionString );
       var options = optionsBuilder.Options;
       return new ApiDbContext(options); // Error occurs here

上下文类包含

public class ApiDbContext : DbContext

    public ApiDbContext(DbContextOptions<ApiDbContext> options)
        : base(options)
    
    
 // etc

我设法通过创建一个框架控制台 exe 来解决这个问题,然后让 vb6 对其进行处理。

Dim num As Long
num = ShellSync(cmd, vbMinimizedNoFocus)

shellsync 的代码在模块中的位置

Option Explicit
Private Const INFINITE = &HFFFFFFFF
Private Const SYNCHRONIZE = &H100000
Private Const PROCESS_QUERY_INFORMATION = &H400&

Private Declare Function CloseHandle Lib "kernel32" ( _
    ByVal hObject As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" ( _
    ByVal hProcess As Long, _
    lpExitCode As Long) As Long

Private Declare Function OpenProcess Lib "kernel32" ( _
    ByVal dwDesiredAccess As Long, _
    ByVal bInheritHandle As Long, _
    ByVal dwProcessId As Long) As Long

Private Declare Function WaitForSingleObject Lib "kernel32" ( _
    ByVal hHandle As Long, _
    ByVal dwMilliseconds As Long) As Long

Public Function ShellSync( _
    ByVal PathName As String, _
    ByVal WindowStyle As VbAppWinStyle) As Long
    'Shell and wait.  Return exit code result, raise an
    'exception on any error.
    Dim lngPid As Long
    Dim lngHandle As Long
    Dim lngExitCode As Long

    lngPid = Shell(PathName, WindowStyle)
    If lngPid <> 0 Then
        lngHandle = OpenProcess(SYNCHRONIZE _
                             Or PROCESS_QUERY_INFORMATION, 0, lngPid)
        If lngHandle <> 0 Then
            WaitForSingleObject lngHandle, INFINITE
            If GetExitCodeProcess(lngHandle, lngExitCode) <> 0 Then
                ShellSync = lngExitCode
                CloseHandle lngHandle
            Else
                CloseHandle lngHandle
                Err.Raise &H8004AA00, "ShellSync", _
                          "Failed to retrieve exit code, error " _
                        & CStr(Err.LastDllError)
            End If
        Else
            Err.Raise &H8004AA01, "ShellSync", _
                      "Failed to open child process"
        End If
    Else
        Err.Raise &H8004AA02, "ShellSync", _
                  "Failed to Shell child process"
    End If
End Function

有趣的是,如果我调用 shell 而不是 shellsync 我会得到错误

System.Exception: kg1System.IO.FileNotFoundException: Could not load file or assembly 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
   at SBDSTD.Standard.Helpers.LogHelper.LogMessage(String message, 

[更新]

我将以下代码添加到 com 可见库中

    [DispId(2)]
    [ComVisible(true)]
    public string ReferenceCheck()
    
        var factory = new Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory();
        return "";
    

但它没有帮助。

我尝试使用Fuslogvw,但日志查看器为空,即使我将设置更改为登录异常文本和attempt to troubleshoot

我尝试使用 Procmon 并且可以看到以下内容

我还尝试从“调试”菜单中找到“模块”窗口,但没有看到它。

检查This link

[更新]

我注意到我已关闭程序集绑定日志记录。

但是当我查看 RegEdit 时,它已经是 1

[更新]

阅读汉斯·帕桑特的评论后 在 com 可见库中我添加了some code to resolve assemblies

我在com可见库中的测试方法显示如下错误信息。

System.TypeInitializationException: 
The type initializer for 'Microsoft.Data.SqlClient.TdsParser' 
threw an exception. ---> 
System.TypeInitializationException: 
The type initializer for 'Microsoft.Data.SqlClient.SNILoadHandle' threw an exception. 
---> System.TypeInitializationException: 
The type initializer for 'Microsoft.Data.SqlClient.SNINativeMethodWrapper' threw an exception. ---> 
System.ComponentModel.Win32Exception: Failed to load C:\Dev2\UnitTestProjectStandard\bin\Debug\x86\SNI.dll ---> System.ComponentModel.Win32Exception: 
The specified module could not be found
  Stack Trace: 
    SNINativeMethodWrapper.cctor() line 64
    --- End of inner exception stack trace ---
    SNINativeMethodWrapper.SNIInitialize()
    SNILoadHandle.ctor() line 36
    SNILoadHandle.cctor() line 17
    --- End of inner exception stack trace ---
    TdsParser.cctor() line 166
    --- End of inner exception stack trace ---
    DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) line 1411
    DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) line 1310
    DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) line 357
    DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) line 773
    DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) line 72
    SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) line 1860
    SqlConnection.TryOpen(TaskCompletionSource`1 retry) line 1853
    SqlConnection.Open() line 1421
    RelationalConnection.OpenDbConnection(Boolean errorsExpected)
    RelationalConnection.Open(Boolean errorsExpected)
    RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
    Enumerator.InitializeReader(DbContext _, Boolean result)
    SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
    Enumerator.MoveNext()
    Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
    lambda_method(Closure , QueryContext )
    QueryCompiler.Execute[TResult](Expression query)
    EntityQueryProvider.Execute[TResult](Expression expression)
    Queryable.FirstOrDefault[TSource](IQueryable`1 source)

[更新]

This issue on GitHub seems related

我尝试重新安装 c** redistributable

[更新]

我终于让 Fuslogvw 与 the help of this question 合作了

其中引用了问题库的 2 个版本。

我还注意到我的标准库有一个分析器在抱怨

0 is an internal API that supports the Entity Framework Core infrastructure and not subject to the same compatibility standards as public APIs. It may be changed or removed without notice in any release.

[更新]

如果我在我的 com 可见框架项目中创建一个 .exe 并运行它,就没有问题。如果我尝试进行单元测试,就会出现问题。

Fusion 日志显示如下

   *** Assembly Binder Log Entry  (02-Mar-20 @ 7:54:23 AM) ***

The operation failed.
Bind result: hr = 0x80131040. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: DisplayName = Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
 (Fully-specified)
LOG: Appbase = file:///C:/Dev2/Combridge/SBD.ComBridge/UnitTestProject1/bin/Debug
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = NULL
Calling assembly : Microsoft.Extensions.DependencyInjection, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Dev2/Combridge/SBD.ComBridge/UnitTestProject1/bin/Debug/Microsoft.Extensions.DependencyInjection.Abstractions.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\Dev2\Combridge\SBD.ComBridge\UnitTestProject1\bin\Debug\Microsoft.Extensions.DependencyInjection.Abstractions.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: The assembly reference did not match the assembly definition found.
ERR: Run-from-source setup phase failed with hr = 0x80131040.
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

*** Assembly Binder Log Entry  (02-Mar-20 @ 7:54:23 AM) ***

The operation failed.
Bind result: hr = 0x80131040. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: DisplayName = Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
 (Fully-specified)
LOG: Appbase = file:///C:/Dev2/Combridge/SBD.ComBridge/UnitTestProject1/bin/Debug
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = NULL
Calling assembly : Microsoft.Extensions.DependencyInjection, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Dev2/Combridge/SBD.ComBridge/UnitTestProject1/bin/Debug/Microsoft.Extensions.DependencyInjection.Abstractions.DLL.
LOG: Assembly download was successful. Attempting setup of file: C:\Dev2\Combridge\SBD.ComBridge\UnitTestProject1\bin\Debug\Microsoft.Extensions.DependencyInjection.Abstractions.dll
LOG: Entering run-from-source setup phase.
LOG: Assembly Name is: Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.2.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: The assembly reference did not match the assembly definition found.
ERR: Run-from-source setup phase failed with hr = 0x80131040.
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

我注意到一些版本差异!

我尝试在另一台装有 VS 16.4.4 的机器上运行测试,以防 Visual Studio 的预览版出现问题,但问题再次出现。

在我的框架测试项目中,我尝试了 Microsoft.Extensions.DependencyInjectionAbstractions 的 installing the 3.1.1 version 并注意到一个警告

Severity    Code    Description Project File    Line    Suppression State
Warning NU1605  Detected package downgrade: Microsoft.Extensions.DependencyInjection.Abstractions from 3.1.2 to 3.1.1. Reference the package directly from the project to select a different version. 
 UnitTestProject1 -> SBD.CombridgeVivadStd -> SBDSTD.Standard 1.0.0-CI-20200301-211054 -> Microsoft.EntityFrameworkCore 3.1.2 -> Microsoft.Extensions.DependencyInjection 3.1.2 -> Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.2) 
 UnitTestProject1 -> Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.1)   UnitTestProject1    C:\Dev2\Combridge\SBD.ComBridge\UnitTestProject1\UnitTestProject1.csproj    1   

我重试了 Simon 手动安装 microsoft.data.sqlclient.sni 的建议

但还是报错

Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0

我也试过下载1.1.1版本的microsoft.data.sqlclient.sni

[更新] 我决定在.netstandard2.0项目中尝试回滚实体框架来使用

 <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.0" />
 <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />

现在,当我使用 com 可见框架项目进行单元测试时,我得到了

 System.Exception: vivadbridgestd:GetValidCarriers line: 20 error:System.Exception: kg1System.IO.FileLoadException: Could not load file or assembly 'System.ComponentModel.Annotations, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
    File name: 'System.ComponentModel.Annotations, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
       at Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure.RelationalConventionSetBuilder.CreateConventionSet()
       at Microsoft.EntityFrameworkCore.Metadata.Conventions.SqlServerConventionSetBuilder.CreateConventionSet()
       at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.RuntimeConventionSetBuilder.CreateConventionSet()
       at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
       at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder)
       at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
       at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
       at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
       at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
       at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
       at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
       at Microsoft.EntityFrameworkCore.DbContext.get_Model()
       at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
       at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
       at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
       at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
       at SBDSTD.Standard.Helpers.LogHelper.InnerLogMessage(String message, JobHeaderLogInfo logInfo, Boolean sendEmail, ApiDbContext connect)

这也会导致我的 exe 失败。

然后我尝试了3.1.0版本的EFCore 我现在在框架测试项目中得到以下内容

Test method UnitTestProject1.UnitTest1.T225_ValidCarriers threw exception: 
System.Exception: vivadbridgestd:GetValidCarriers line: 20 error:System.Exception: kg1System.Exception: Line 53 System.IO.FileLoadException: Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'
   at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.<GetOrAdd>g__BuildServiceProvider|3()
   at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_0.<GetOrAdd>b__2(Int64 k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.GetOrAdd(IDbContextOptions options, Boolean providerRequired)
   at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options)
   at SBDSTD.Standard.Entities.ApiDbContext..ctor(DbContextOptions`1 options)
   at SBDSTD.Standard.Services.Helper.MakeContext(String connectionString)

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: DisplayName = Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
 (Fully-specified)
LOG: Appbase = file:///C:/Dev2/Combridge/SBD.ComBridge/UnitTestProject1/bin/Debug
LOG: Initial PrivatePath = NULL
Calling assembly : Microsoft.Extensions.DependencyInjection, Version=3.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\Extensions\TestPlatform\testhost.x86.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Post-policy reference: Microsoft.Extensions.DependencyInjection.Abstractions, Version=3.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
LOG: Attempting download of new URL file:///C:/Dev2/Combridge/SBD.ComBridge/UnitTestProject1/bin/Debug/Microsoft.Extensions.DependencyInjection.Abstractions.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Build Number
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

   at SBDSTD.Standard.Services.Helper.MakeContext(String connectionString)

也发生在 .exe 中

我想知道this question about entityframework.core 是否相关,但我只能在 Nuget 上找到 Microsoft.EntityFrameworkCore。

[更新单元测试现在有效]

我现在可以进行单元测试了。 我需要在单元测试项目

的顶部附近添加以下内容
   <PropertyGroup>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>    
   </PropertyGroup>

如讨论in this question on assembly binding

但是我仍然需要解决在 VB6 中使用我的 com 可见库

【问题讨论】:

检查***.com/questions/34772164/…的解决方案 ***.com/questions/19774155/… 我有大量的 C# 代码从 C# 通过 COM 运行,所以我认为这应该是可以解决的。出于某种原因,即使加载了其他 .NET 依赖项,Microsoft.Extensions.DependencyInjection.Abstractions 也不会加载。 DLL有64位代码的机会吗?它在 GAC 中吗? 这是标准的 DLL Hell 问题,CLR 只查找依赖程序集的两个位置。 GAC和EXE文件所在的路径,都没有那个文件。 搜索 [ComVisible] 程序集所在的位置。在三个标准解决方案中,有两个不符合条件,因为这是一个 .NETStandard 程序集。左一,你需要 AppDomain.AssemblyResolve 去。往往需要一个 God 接口,以便您可以尽快订阅事件,这是客户端代码必须首先创建的事件,类似于 Office 互操作中使用的 Application。 您是否尝试按照微软的指南通过 COM 公开 .NET Core 3+ 库? docs.microsoft.com/en-us/dotnet/core/native-interop/… 【参考方案1】:

我一直在努力解决完全相同的问题并且能够解决它。

在我的情况下,问题 DLL 是 Microsoft.Extensions.Logging。这是我的例外:

Could not load file or assembly 'System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Extensions.Logging, 
Version=2.2.0.0, Culture=neutral, 
PublicKeyToken=adb9793829ddae60' or one of its dependencies. 
The system cannot find the file specified.

解决方案非常简单,基本上app.config 适用于消耗 COM 公开的 .NET 类的 VB6 EXE。您只需要使用您的 &lt;assemblyBinding&gt; 标签创建一个常规的 app.config 即可。棘手的部分是放置此配置的位置以及如何命名。

    从 IDE (VB6) 运行 EXE 时,在 C:\Program Files (x86)\Microsoft Visual Studio\VB98 中创建 VB6.exe.config。创建配置后不要忘记重新启动 IDE。 当您从 EXE 直接运行时,在与您的 ExeName.exe 相同的文件夹中创建 ExeName.exe.config

这里是 Fusion 日志,说明它如何在更改后解决重定向(从 IDE 案例运行):

Calling assembly : Unity.Microsoft.Logging, Version=5.11.1.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0.
===
LOG: This bind starts in LoadFrom load context.
WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
LOG: Using application configuration file: C:\Program Files (x86)\Microsoft Visual Studio\VB98\VB6.EXE.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 2.2.0.0 redirected to 5.0.0.0.
LOG: Post-policy reference: Microsoft.Extensions.Logging, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
LOG: Binding succeeds. Returns assembly from C:\Program Files (x86)\Retail\Common\Microsoft.Extensions.Logging.dll.
LOG: Assembly is loaded in LoadFrom load context.

【讨论】:

以上是关于无法使用 COM 加载文件或程序集“Microsoft.Extensions.DependencyInjection.Abstractions”的主要内容,如果未能解决你的问题,请参考以下文章

由于版本冲突,无法加载某个程序集

无法加载文件或程序集,但已加载

无法加载文件或程序集

寻找解决策略:无法加载文件或程序集[重复]

无法加载文件或程序集“Microsoft.ReportViewer.WebForms”

Tizen.NET 调试错误无法加载文件或程序集'Samsung.Sap