fix native extension loading in .NET5 single-file deployments

pull/24744/head
Jan Tattermusch 4 years ago
parent 53390d9c42
commit 1f9f3c7eae
  1. 17
      src/csharp/Grpc.Core/Internal/NativeExtension.cs

@ -84,7 +84,7 @@ namespace Grpc.Core.Internal
{ {
// TODO: allow customizing path to native extension (possibly through exposing a GrpcEnvironment property). // TODO: allow customizing path to native extension (possibly through exposing a GrpcEnvironment property).
// See https://github.com/grpc/grpc/pull/7303 for one option. // See https://github.com/grpc/grpc/pull/7303 for one option.
var assemblyDirectory = Path.GetDirectoryName(GetAssemblyPath()); var assemblyDirectory = GetAssemblyDirectory();
// With "classic" VS projects, the native libraries get copied using a .targets rule to the build output folder // With "classic" VS projects, the native libraries get copied using a .targets rule to the build output folder
// alongside the compiled assembly. // alongside the compiled assembly.
@ -151,13 +151,20 @@ namespace Grpc.Core.Internal
return new NativeMethods(new NativeMethods.DllImportsFromStaticLib()); return new NativeMethods(new NativeMethods.DllImportsFromStaticLib());
} }
private static string GetAssemblyPath() private static string GetAssemblyDirectory()
{ {
var assembly = typeof(NativeExtension).GetTypeInfo().Assembly; var assembly = typeof(NativeExtension).GetTypeInfo().Assembly;
#if NETSTANDARD #if NETSTANDARD
// Assembly.EscapedCodeBase does not exist under CoreCLR, but assemblies imported from a nuget package // Assembly.EscapedCodeBase does not exist under CoreCLR, but assemblies imported from a nuget package
// don't seem to be shadowed by DNX-based projects at all. // don't seem to be shadowed by DNX-based projects at all.
return assembly.Location; var assemblyLocation = assembly.Location;
if (!string.IsNullOrEmpty(assemblyLocation))
{
return Path.GetDirectoryName(assemblyLocation);
}
// In .NET5 single-file deployments, assembly.Location won't be available
// Also see https://docs.microsoft.com/en-us/dotnet/core/deploying/single-file#other-considerations
return AppContext.BaseDirectory;
#else #else
// If assembly is shadowed (e.g. in a webapp), EscapedCodeBase is pointing // If assembly is shadowed (e.g. in a webapp), EscapedCodeBase is pointing
// to the original location of the assembly, and Location is pointing // to the original location of the assembly, and Location is pointing
@ -167,9 +174,9 @@ namespace Grpc.Core.Internal
var escapedCodeBase = assembly.EscapedCodeBase; var escapedCodeBase = assembly.EscapedCodeBase;
if (IsFileUri(escapedCodeBase)) if (IsFileUri(escapedCodeBase))
{ {
return new Uri(escapedCodeBase).LocalPath; return Path.GetDirectoryName(new Uri(escapedCodeBase).LocalPath);
} }
return assembly.Location; return Path.GetDirectoryName(assembly.Location);
#endif #endif
} }

Loading…
Cancel
Save