Skip to content

System.Runtime.CompilerServices.Unsafe Assembly Loading Issue in Excel Add-in Environment #151

@yangf85

Description

@yangf85

Issue Description

When using CommunityToolkit.Mvvm version 8.4.0 in an Excel add-in built with Excel-DNA and .NET Framework 4.8, I encounter a persistent System.IO.FileLoadException when calling WeakReferenceMessenger.Default.Register<T>().

Environment

  • CommunityToolkit.Mvvm: 8.4.0
  • Target Framework: .NET Framework 4.8
  • Platform: Excel Add-in using Excel-DNA 1.8.0
  • Project Type: SDK-style project (<Project Sdk="Microsoft.NET.Sdk">)
  • OS: Windows 10/11
  • Excel Version: Microsoft Excel (Office 365)

Error Details

Exception Stack Trace

System.IO.FileLoadException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=6.1.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)
  Source: CommunityToolkit.Mvvm
  at CommunityToolkit.Mvvm.Messaging.WeakReferenceMessenger.Register[TMessage,TToken](Object recipient, TToken token, MessageHandlerDispatcher dispatcher)
  at CommunityToolkit.Mvvm.Messaging.WeakReferenceMessenger.Register[TMessage,TToken](IRecipient`1 recipient, TToken token)
  at CommunityToolkit.Mvvm.Messaging.IMessengerExtensions.Register[TMessage](IMessenger messenger, IRecipient`1 recipient)
  
Inner Exception:
FileLoadException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=6.0.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)

Key Observations

  1. The outer exception expects System.Runtime.CompilerServices.Unsafe version 6.1.0.0
  2. The inner exception shows the runtime is actually trying to load version 6.0.0.0
  3. The correct version (6.1.0.0) is present in the output directory and verified via reflection
  4. The issue only occurs in Excel add-in environment, not in regular applications

Reproduction Code

Project File (.csproj)

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net48</TargetFramework>
    <UseWPF>true</UseWPF>
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
    <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>
  
  <ItemGroup>
    <PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
    <PackageReference Include="ExcelDna.AddIn" Version="1.8.0" />
    <PackageReference Include="ExcelDna.Integration" Version="1.8.0" />
    <!-- Other packages... -->
  </ItemGroup>
</Project>

App.config

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe"
                          publicKeyToken="b03f5f7f11d50a3a"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.1.0.0" newVersion="6.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Failing Code

public class OrderManageViewModel
{
    public OrderManageViewModel(IDataService data)
    {
        // This line throws the exception
        WeakReferenceMessenger.Default.Register<string>(this);
    }
}

What I've Tried

1. Verified Assembly Versions

  • Confirmed System.Runtime.CompilerServices.Unsafe.dll version 6.1.0.0 is in the bin directory
  • Used reflection to verify the assembly version matches expectations
  • Checked that all related assemblies (System.Memory, System.Buffers) are correct versions

2. Assembly Binding Redirects

  • Added comprehensive binding redirects in app.config
  • Tried both auto-generated and manual binding redirects
  • Verified redirects cover the full version range (0.0.0.0-6.1.0.0 → 6.1.0.0)

3. Custom Assembly Resolution

// Tried multiple approaches including:
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
    // Custom assembly loading logic
    // Using Assembly.LoadFrom(), Assembly.LoadFile(), Assembly.Load(byte[])
};

4. Package Version Combinations

  • Tried explicit references to System.Runtime.CompilerServices.Unsafe versions 6.0.0, 6.1.0
  • Attempted downgrading CommunityToolkit.Mvvm to 8.2.2 (which expects 6.0.0)
  • Verified package dependency chains

5. Excel-DNA Specific Solutions

  • Tried configuring external libraries in .dna files
  • Attempted various CopyLocalLockFileAssemblies and build settings

Expected Behavior

WeakReferenceMessenger.Default.Register<T>() should work without assembly loading exceptions, as it does in regular .NET applications.

Actual Behavior

Consistent FileLoadException with version mismatch, despite correct assemblies being present and properly configured.

Additional Context

Build Output (showing correct resolution)

检测到包降级: System.Runtime.CompilerServices.Unsafe 从 6.1.0 降级到 6.0.0
Cyclone.ExcelToolkit -> CommunityToolkit.Mvvm 8.4.0 -> System.Runtime.CompilerServices.Unsafe (>= 6.1.0)

This suggests the build system correctly resolves to 6.1.0, but runtime loading fails.

Excel Add-in Specific Context

This issue appears to be specific to Excel add-in environments where:

  1. The CLR is hosted by Excel rather than being the primary application host
  2. Assembly loading behavior may differ from standard .NET applications
  3. Multiple AppDomains or assembly contexts might be involved

Questions

  1. Is this a known issue with CommunityToolkit.Mvvm in hosted CLR environments like Excel add-ins?

  2. Are there specific recommendations for using CommunityToolkit.Mvvm in Excel-DNA or similar COM add-in scenarios?

  3. Could the library provide better error handling or diagnostics for assembly loading issues?

  4. Is there a way to make CommunityToolkit.Mvvm more resilient to version mismatches of System.Runtime.CompilerServices.Unsafe?

Possible Solutions

Would any of these approaches be feasible for the library:

  1. Internal Assembly Resolution: Could CommunityToolkit.Mvvm include its own assembly resolution logic for critical dependencies?

  2. Version Tolerance: Could the library be more tolerant of minor version differences in System.Runtime.CompilerServices.Unsafe?

  3. Initialization Method: Could there be an explicit initialization method that pre-loads dependencies before first use?

Thank you for this excellent library! Any guidance on resolving this Excel add-in compatibility issue would be greatly appreciated.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions