Skip to content

Comments

Fix DllImportResolver#27397

Open
tianleiwu wants to merge 2 commits intomainfrom
tlwu/fix_dll_import_resolver
Open

Fix DllImportResolver#27397
tianleiwu wants to merge 2 commits intomainfrom
tlwu/fix_dll_import_resolver

Conversation

@tianleiwu
Copy link
Contributor

@tianleiwu tianleiwu commented Feb 20, 2026

Description

This PR addresses two issues related to the newly added DllImportResolver for .NET native library loading:

  1. Fix IL3000 Warning during Native AOT / Single-File Publish
    When publishing projects that reference Microsoft.ML.OnnxRuntime as a single file or using Native AOT in .NET 9, the compiler reports an IL3000 warning/error because DllImportResolver accesses Assembly.Location. In these deployment models, Assembly.Location always returns an empty string or throws.
    Since DllImportResolver already correctly handles the empty string failure and falls back to AppContext.BaseDirectory (which is fully supported), this PR adds the [UnconditionalSuppressMessage] attribute to suppress the build warning statically.

  2. Fix TypeInitializationException in NativeMethods Static Constructor
    Users reported a System.TypeInitializationException: The type initializer for 'Microsoft.ML.OnnxRuntime.NativeMethods' threw an exception. when initializing the ONNX Runtime environment.
    This occurs because the DllImportResolver (registered in the static constructor) is invoked on the first P/Invoke (OrtGetApiBase). If any API within the resolver throws an unhandled exception (for instance, AppContext.BaseDirectory throwing AppDomainUnloadedException in sandboxed AppDomains or Environment.GetEnvironmentVariable throwing SecurityException), the exception bubbles up and crashes the application with a type initialization failure.
    This PR wraps the DllImportResolver logic in a try-catch block (specifically handling AppContext.BaseDirectory edge cases) so that any resolution failure safely swallows the error and falls back to IntPtr.Zero, allowing the default .NET Platform Invoke mechanism to take over and throw a standard DllNotFoundException instead of a fatal type initialization crash.
    A unit test (TestDllImportResolverDoesNotThrow) has been added to OrtEnvTests.cs to verify that DllImportResolver successfully swallows internal exceptions without crashing the initialization process.

Motivation and Context

These changes ensure that .NET developers can safely compile Native AOT/Single-File applications without build errors and prevent hard application crashes in environments with restricted permissions.

@eserscor
Copy link
Contributor

Is it possible to add a test so we don't regress again?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants