Skip to content

Commit

Permalink
Support single file in DependencyModel (#48790)
Browse files Browse the repository at this point in the history
* Support single file in DependencyModel

When used in a single file application, Assembly.CodeBase will throw an exception. Check for this situation by checking if Assembly.Location is empty before trying to probe next to the assembly.

Fix #47527
  • Loading branch information
eerhardt authored Feb 26, 2021
1 parent c396084 commit d0616f8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,15 @@ private DependencyContext LoadAssemblyContext(Assembly assembly, IDependencyCont

private string GetDepsJsonPath(Assembly assembly)
{
string depsJsonFile = Path.ChangeExtension(assembly.Location, DepsJsonExtension);
// Assemblies loaded in memory (e.g. single file) return empty string from Location.
// In these cases, don't try probing next to the assembly.
string assemblyLocation = assembly.Location;
if (string.IsNullOrEmpty(assemblyLocation))
{
return null;
}

string depsJsonFile = Path.ChangeExtension(assemblyLocation, DepsJsonExtension);
bool depsJsonFileExists = _fileSystem.File.Exists(depsJsonFile);

if (!depsJsonFileExists)
Expand All @@ -136,7 +144,7 @@ private string GetDepsJsonPath(Assembly assembly)
// and CodeBase will be different, so also try the CodeBase
string assemblyCodeBase = GetNormalizedCodeBasePath(assembly);
if (!string.IsNullOrEmpty(assemblyCodeBase) &&
assembly.Location != assemblyCodeBase)
assemblyLocation != assemblyCodeBase)
{
depsJsonFile = Path.ChangeExtension(assemblyCodeBase, DepsJsonExtension);
depsJsonFileExists = _fileSystem.File.Exists(depsJsonFile);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using FluentAssertions;
using System.IO;
using System.Reflection;
using Xunit;

Expand Down Expand Up @@ -90,5 +91,19 @@ public void LoadReturnsNullWhenNotFound()
var loader = new DependencyContextLoader();
Assert.Null(loader.Load(typeof(Moq.Mock).Assembly));
}

[Fact]
public void LoadReturnsNullWhenAssemblyLocationIsEmpty()
{
var loader = new DependencyContextLoader();
Assert.Null(loader.Load(new EmptyLocationAssembly()));
}

private class EmptyLocationAssembly : Assembly
{
public override string Location => string.Empty;
public override AssemblyName GetName() => new AssemblyName("EmptyLocation");
public override Stream? GetManifestResourceStream(string name) => null;
}
}
}

0 comments on commit d0616f8

Please sign in to comment.