Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use AssemblyLoadContext to load EFC.Design #35527

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/EFCore.Tasks/Tasks/Internal/OperationTaskBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ public abstract class OperationTaskBase : ToolTask
/// </summary>
public ITaskItem? StartupAssembly { get; set; }

/// <summary>
/// The location of Microsoft.EntityFrameworkCore.Design.dll
/// </summary>
public ITaskItem? DesignAssembly { get; set; }

/// <summary>
/// The target framework moniker.
/// </summary>
Expand Down Expand Up @@ -188,13 +193,17 @@ protected override string GenerateCommandLineCommands()
args.Add(runtimeFrameworkVersion);
}

#if !NET10_0
#elif NET472
#error Target framework needs to be updated here
#endif
args.Add(
Path.Combine(
Path.GetDirectoryName(typeof(OperationTaskBase).Assembly.Location)!,
"..",
"..",
"tools",
"netcoreapp2.0",
"net10.0",
"ef.dll"));

args.AddRange(AdditionalArguments);
Expand All @@ -207,6 +216,12 @@ protected override string GenerateCommandLineCommands()
args.Add(Path.ChangeExtension(StartupAssembly.ItemSpec, ".dll"));
}

if (DesignAssembly != null)
{
args.Add("--design-assembly");
args.Add(DesignAssembly.ItemSpec);
}

if (Project != null)
{
args.Add("--project");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ For Publish:
Properties="Configuration=$(Configuration);Platform=$(Platform);_EFGenerationStage=$(_EFGenerationStage)" />
</Target>

<Target Name="OptimizeDbContext">
<Target Name="OptimizeDbContext" DependsOnTargets="ResolvePackageAssets">
<PropertyGroup>
<EFRootNamespace Condition="'$(EFRootNamespace)'==''">$(RootNamespace)</EFRootNamespace>
<EFRootNamespace Condition="'$(EFRootNamespace)'==''">$(AssemblyName)</EFRootNamespace>
Expand All @@ -90,9 +90,14 @@ For Publish:
<EFNullable Condition="'$(EFNullable)'==''">false</EFNullable>
</PropertyGroup>

<ItemGroup>
<DesignAssembly Include="@(RuntimeCopyLocalItems)" Condition="$([System.String]::Copy('%(FullPath)').EndsWith('Microsoft.EntityFrameworkCore.Design.dll'))" />
</ItemGroup>

<OptimizeDbContext Assembly="$(_AssemblyFullName)"
StartupAssembly="$(EFStartupAssembly)"
ProjectAssetsFile="$(ProjectAssetsFile)"
DesignAssembly="@(DesignAssembly->'%(FullPath)')"
RuntimeFrameworkVersion="$(RuntimeFrameworkVersion)"
TargetFrameworkMoniker="$(TargetFrameworkMoniker)"
DbContextType="$(DbContextType)"
Expand Down
9 changes: 9 additions & 0 deletions src/EFCore.Tools/tools/EntityFrameworkCore.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -1329,6 +1329,15 @@ function EF($project, $startupProject, $params, $applicationArgs, [switch] $skip
$params += '--nullable'
}

# NB: -join is here to support ConvertFrom-Json on PowerShell 3.0
$references = (dotnet build $startupProject.FullName /t:ResolvePackageAssets /getItem:RuntimeCopyLocalItems) -join "`n" | ConvertFrom-Json

$designReference = $references.Items.RuntimeCopyLocalItems | ? { $_.FullPath.EndsWith('Microsoft.EntityFrameworkCore.Design.dll') }
if ($designReference -ne $null)
{
$params += '--design-assembly', $designReference.FullPath
}

$arguments = ToArguments $params
if ($applicationArgs)
{
Expand Down
101 changes: 54 additions & 47 deletions src/dotnet-ef/Project.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public Project(string file, string? framework, string? configuration, string? ru
public string ProjectName { get; }

public string? AssemblyName { get; set; }
public string? DesignAssembly { get; set; }
public string? Language { get; set; }
public string? OutputPath { get; set; }
public string? PlatformTarget { get; set; }
Expand All @@ -50,78 +51,84 @@ public static Project FromFile(
{
Debug.Assert(!string.IsNullOrEmpty(file), "file is null or empty.");

IDictionary<string, string> metadata;
var metadataFile = Path.GetTempFileName();
try
{
var args = new List<string>
var args = new List<string>
{
"msbuild",
};

if (framework != null)
{
args.Add($"/property:TargetFramework={framework}");
}
if (framework != null)
{
args.Add($"/property:TargetFramework={framework}");
}

if (configuration != null)
{
args.Add($"/property:Configuration={configuration}");
}
if (configuration != null)
{
args.Add($"/property:Configuration={configuration}");
}

if (runtime != null)
{
args.Add($"/property:RuntimeIdentifier={runtime}");
}
if (runtime != null)
{
args.Add($"/property:RuntimeIdentifier={runtime}");
}

foreach (var property in typeof(Project).GetProperties())
{
args.Add($"/getProperty:{property.Name}");
}
foreach (var property in typeof(Project).GetProperties())
{
args.Add($"/getProperty:{property.Name}");
}

args.Add("/getProperty:Platform");
args.Add("/getProperty:Platform");

args.Add(file);
args.Add("/t:ResolvePackageAssets");
args.Add("/getItem:RuntimeCopyLocalItems");

var output = new StringBuilder();
args.Add(file);

var exitCode = Exe.Run("dotnet", args, handleOutput: line => output.AppendLine(line));
if (exitCode != 0)
{
throw new CommandException(Resources.GetMetadataFailed);
}
var output = new StringBuilder();

metadata = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(output.ToString())!["Properties"];
}
finally
var exitCode = Exe.Run("dotnet", args, handleOutput: line => output.AppendLine(line));
if (exitCode != 0)
{
File.Delete(metadataFile);
throw new CommandException(Resources.GetMetadataFailed);
}

var platformTarget = metadata[nameof(PlatformTarget)];
var metadata = JsonSerializer.Deserialize<ProjectMetadata>(output.ToString())!;

var designAssembly = metadata.Items["RuntimeCopyLocalItems"]
.Select(i => i["FullPath"])
.FirstOrDefault(i => i.Contains("Microsoft.EntityFrameworkCore.Design", StringComparison.InvariantCulture));
var properties = metadata.Properties;

var platformTarget = properties[nameof(PlatformTarget)];
if (platformTarget.Length == 0)
{
platformTarget = metadata["Platform"];
platformTarget = properties["Platform"];
}

return new Project(file, framework, configuration, runtime)
{
AssemblyName = metadata[nameof(AssemblyName)],
Language = metadata[nameof(Language)],
OutputPath = metadata[nameof(OutputPath)],
AssemblyName = properties[nameof(AssemblyName)],
DesignAssembly = designAssembly,
Language = properties[nameof(Language)],
OutputPath = properties[nameof(OutputPath)],
PlatformTarget = platformTarget,
ProjectAssetsFile = metadata[nameof(ProjectAssetsFile)],
ProjectDir = metadata[nameof(ProjectDir)],
RootNamespace = metadata[nameof(RootNamespace)],
RuntimeFrameworkVersion = metadata[nameof(RuntimeFrameworkVersion)],
TargetFileName = metadata[nameof(TargetFileName)],
TargetFrameworkMoniker = metadata[nameof(TargetFrameworkMoniker)],
Nullable = metadata[nameof(Nullable)],
TargetFramework = metadata[nameof(TargetFramework)],
TargetPlatformIdentifier = metadata[nameof(TargetPlatformIdentifier)]
ProjectAssetsFile = properties[nameof(ProjectAssetsFile)],
ProjectDir = properties[nameof(ProjectDir)],
RootNamespace = properties[nameof(RootNamespace)],
RuntimeFrameworkVersion = properties[nameof(RuntimeFrameworkVersion)],
TargetFileName = properties[nameof(TargetFileName)],
TargetFrameworkMoniker = properties[nameof(TargetFrameworkMoniker)],
Nullable = properties[nameof(Nullable)],
TargetFramework = properties[nameof(TargetFramework)],
TargetPlatformIdentifier = properties[nameof(TargetPlatformIdentifier)]
};
}

private record class ProjectMetadata
{
public Dictionary<string, string> Properties { get; set; } = null!;
public Dictionary<string, Dictionary<string, string>[]> Items { get; set; } = null!;
}

public void Build(IEnumerable<string>? additionalArgs)
{
var args = new List<string> { "build" };
Expand Down
7 changes: 7 additions & 0 deletions src/dotnet-ef/RootCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,13 @@ protected override int Execute(string[] _)
args.Add("--framework");
args.Add(startupProject.TargetFramework!);

var designAssembly = startupProject.DesignAssembly;
if (!string.IsNullOrEmpty(designAssembly))
{
args.Add("--design-assembly");
args.Add(designAssembly);
}

if (_configuration.HasValue())
{
args.Add("--configuration");
Expand Down
31 changes: 28 additions & 3 deletions src/ef/AppDomainOperationExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

#if NET472
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Design.Internal;
Expand All @@ -18,11 +16,13 @@ internal class AppDomainOperationExecutor : OperationExecutorBase
private readonly object _executor;
private readonly AppDomain _domain;
private bool _disposed;
private string? _efcoreVersion;
private const string ReportHandlerTypeName = "Microsoft.EntityFrameworkCore.Design.OperationReportHandler";

public AppDomainOperationExecutor(
string assembly,
string? startupAssembly,
string? designAssembly,
string? project,
string? projectDir,
string? dataDirectory,
Expand All @@ -31,7 +31,7 @@ public AppDomainOperationExecutor(
bool nullable,
string[] remainingArguments,
IOperationReportHandler reportHandler)
: base(assembly, startupAssembly, project, projectDir, rootNamespace, language, nullable, remainingArguments, reportHandler)
: base(assembly, startupAssembly, designAssembly, project, projectDir, rootNamespace, language, nullable, remainingArguments, reportHandler)
{
var info = new AppDomainSetup { ApplicationBase = AppBasePath };

Expand Down Expand Up @@ -66,6 +66,15 @@ public AppDomainOperationExecutor(
null,
null);

if (DesignAssemblyPath != null)
{
_domain.AssemblyResolve += (object? sender, ResolveEventArgs args) =>
{
var assemblyPath = Path.Combine(Path.GetDirectoryName(DesignAssemblyPath)!, args.Name + ".dll");
return File.Exists(assemblyPath) ? Assembly.LoadFrom(assemblyPath) : null;
};
}

_executor = _domain.CreateInstanceAndUnwrap(
DesignAssemblyName,
ExecutorTypeName,
Expand All @@ -91,6 +100,22 @@ public AppDomainOperationExecutor(
null);
}

public override string? EFCoreVersion
{
get
{
if (_efcoreVersion != null)
{
return _efcoreVersion;
}

var designAssembly = _domain.GetAssemblies().Single(assembly => assembly.GetName().Name == DesignAssemblyName);
_efcoreVersion = designAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion;
return _efcoreVersion;
}
}

protected override object CreateResultHandler()
=> new OperationResultHandler();

Expand Down
4 changes: 2 additions & 2 deletions src/ef/Commands/DbContextOptimizeCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,12 @@ protected override void Validate()

protected override int Execute(string[] args)
{
if (new SemanticVersionComparer().Compare(EFCoreVersion, "6.0.0") < 0)
using var executor = CreateExecutor(args);
if (new SemanticVersionComparer().Compare(executor.EFCoreVersion, "6.0.0") < 0)
{
throw new CommandException(Resources.VersionRequired("6.0.0"));
}

using var executor = CreateExecutor(args);
var result = executor.OptimizeContext(
_outputDir!.Value(),
_namespace!.Value(),
Expand Down
14 changes: 8 additions & 6 deletions src/ef/Commands/MigrationsBundleCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,16 @@ protected override int Execute(string[] args)
#else
protected override int Execute(string[] args)
{
if (new SemanticVersionComparer().Compare(EFCoreVersion, "6.0.0") < 0)
{
throw new CommandException(Resources.VersionRequired("6.0.0"));
}

string? version;
string context;
using (var executor = CreateExecutor(args))
{
version = executor.EFCoreVersion;
if (new SemanticVersionComparer().Compare(version, "6.0.0") < 0)
{
throw new CommandException(Resources.VersionRequired("6.0.0"));
}

context = (string)executor.GetContextInfo(Context!.Value())["Type"]!;
}

Expand All @@ -53,7 +55,7 @@ protected override int Execute(string[] args)
Session = new Dictionary<string, object>
{
["TargetFramework"] = Framework!.Value()!,
["EFCoreVersion"] = EFCoreVersion!,
["EFCoreVersion"] = version!,
["Project"] = Project!.Value()!,
["StartupProject"] = StartupProject!.Value()!
}
Expand Down
5 changes: 2 additions & 3 deletions src/ef/Commands/MigrationsHasPendingModelChangesCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,12 @@ internal partial class MigrationsHasPendingModelChangesCommand
{
protected override int Execute(string[] args)
{
if (new SemanticVersionComparer().Compare(EFCoreVersion, "8.0.0") < 0)
using var executor = CreateExecutor(args);
if (new SemanticVersionComparer().Compare(executor.EFCoreVersion, "8.0.0") < 0)
{
throw new CommandException(Resources.VersionRequired("8.0.0"));
}

using var executor = CreateExecutor(args);

executor.HasPendingModelChanges(Context!.Value());

return base.Execute(args);
Expand Down
Loading