Skip to content

Commit f678908

Browse files
authored
Discover the migrations-bundle DbContext out-of-process so publish doesn't lock the assembly (#38456)
Fixes #25555
1 parent a331fb5 commit f678908

14 files changed

Lines changed: 1011 additions & 25 deletions

‎src/EFCore.Tools/tools/EntityFrameworkCore.psm1‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1433,28 +1433,49 @@ function EF($project, $startupProject, $params, $applicationArgs, [switch] $skip
14331433

14341434
$dotnetParams = 'exec', '--depsfile', $depsFile
14351435

1436+
# `migrations bundle` launches a child ef.dll to discover the DbContext, and needs the same host
1437+
# context to start it. Only that command understands these options; the others reject unknown ones.
1438+
$isBundle = $params.Count -ge 2 -and $params[0] -eq 'migrations' -and $params[1] -eq 'bundle'
1439+
$bundleHostParams = @()
1440+
if ($isBundle -and [IO.File]::Exists($depsFile))
1441+
{
1442+
$bundleHostParams += '--deps-file', $depsFile
1443+
}
1444+
14361445
if ($projectAssetsFile)
14371446
{
14381447
# NB: Don't use Get-Content. It doesn't handle UTF-8 without a signature
14391448
# NB: Don't use ReadAllLines. ConvertFrom-Json won't work on PowerShell 3.0
14401449
$projectAssets = [IO.File]::ReadAllText($projectAssetsFile) | ConvertFrom-Json
14411450
$projectAssets.packageFolders.psobject.Properties.Name | %{
14421451
$dotnetParams += '--additionalprobingpath', $_.TrimEnd('\')
1452+
if ($isBundle)
1453+
{
1454+
$bundleHostParams += '--additional-probing-path', $_.TrimEnd('\')
1455+
}
14431456
}
14441457
}
14451458

14461459
if ([IO.File]::Exists($runtimeConfig))
14471460
{
14481461
$dotnetParams += '--runtimeconfig', $runtimeConfig
1462+
if ($isBundle)
1463+
{
1464+
$bundleHostParams += '--runtime-config', $runtimeConfig
1465+
}
14491466
}
14501467
elseif ($runtimeFrameworkVersion)
14511468
{
14521469
$dotnetParams += '--fx-version', $runtimeFrameworkVersion
1470+
if ($isBundle)
1471+
{
1472+
$bundleHostParams += '--runtime-framework-version', $runtimeFrameworkVersion
1473+
}
14531474
}
14541475

14551476
$dotnetParams += $efPath
14561477

1457-
$params = $dotnetParams + $params
1478+
$params = $dotnetParams + $params + $bundleHostParams
14581479
}
14591480
elseif ($targetFramework -eq '.NETStandard')
14601481
{

‎src/dotnet-ef/Exe.cs‎

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,25 +14,16 @@ public static int Run(
1414
string? workingDirectory = null,
1515
Action<string?>? handleOutput = null,
1616
Action<string?>? handleError = null,
17-
Action<string>? processCommandLine = null)
17+
Action<string>? processCommandLine = null,
18+
Encoding? outputEncoding = null)
1819
{
1920
var arguments = ToArguments(args);
2021

2122
processCommandLine ??= Reporter.WriteVerbose;
2223
processCommandLine(executable + " " + arguments);
2324

24-
var startInfo = new ProcessStartInfo
25-
{
26-
FileName = executable,
27-
Arguments = arguments,
28-
UseShellExecute = false,
29-
RedirectStandardOutput = handleOutput != null,
30-
RedirectStandardError = handleError != null
31-
};
32-
if (workingDirectory != null)
33-
{
34-
startInfo.WorkingDirectory = workingDirectory;
35-
}
25+
var startInfo = CreateStartInfo(
26+
executable, arguments, workingDirectory, handleOutput != null, handleError != null, outputEncoding);
3627

3728
var process = new Process { StartInfo = startInfo };
3829

@@ -63,6 +54,45 @@ public static int Run(
6354
return process.ExitCode;
6455
}
6556

57+
// 'outputEncoding' is how the redirected streams are decoded; null keeps the platform default.
58+
internal static ProcessStartInfo CreateStartInfo(
59+
string executable,
60+
string arguments,
61+
string? workingDirectory,
62+
bool redirectOutput,
63+
bool redirectError,
64+
Encoding? outputEncoding)
65+
{
66+
var startInfo = new ProcessStartInfo
67+
{
68+
FileName = executable,
69+
Arguments = arguments,
70+
UseShellExecute = false,
71+
RedirectStandardOutput = redirectOutput,
72+
RedirectStandardError = redirectError
73+
};
74+
75+
if (workingDirectory != null)
76+
{
77+
startInfo.WorkingDirectory = workingDirectory;
78+
}
79+
80+
if (outputEncoding != null)
81+
{
82+
if (redirectOutput)
83+
{
84+
startInfo.StandardOutputEncoding = outputEncoding;
85+
}
86+
87+
if (redirectError)
88+
{
89+
startInfo.StandardErrorEncoding = outputEncoding;
90+
}
91+
}
92+
93+
return startInfo;
94+
}
95+
6696
public static string ToArguments(IReadOnlyList<string> args)
6797
{
6898
var builder = new StringBuilder();
@@ -80,7 +110,7 @@ public static string ToArguments(IReadOnlyList<string> args)
80110
continue;
81111
}
82112

83-
if (args[i].IndexOf(' ') == -1)
113+
if (args[i].IndexOf(' ') == -1 && args[i].IndexOf('"') == -1)
84114
{
85115
builder.Append(args[i]);
86116

‎src/dotnet-ef/RootCommand.cs‎

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,8 @@ protected override int Execute(string[] _)
146146
Resources.PlatformSpecificProject(startupProject.ProjectName, startupProject.TargetFramework));
147147
}
148148

149+
var additionalProbingPaths = new List<string>();
150+
149151
var targetFramework = new FrameworkName(startupProject.TargetFrameworkMoniker!);
150152
if (targetFramework.Identifier == ".NETFramework")
151153
{
@@ -171,21 +173,24 @@ protected override int Execute(string[] _)
171173
using var file = File.OpenRead(projectAssetsFile);
172174
using var reader = JsonDocument.Parse(file);
173175
var projectAssets = reader.RootElement;
174-
var packageFolders = projectAssets.GetProperty("packageFolders").EnumerateObject().Select(p => p.Name);
176+
var packageFolders = projectAssets.GetProperty("packageFolders")
177+
.EnumerateObject().Select(p => Path.TrimEndingDirectorySeparator(p.Name)).ToList();
175178

176179
foreach (var packageFolder in packageFolders)
177180
{
178181
args.Add("--additionalprobingpath");
179-
args.Add(packageFolder.TrimEnd(Path.DirectorySeparatorChar));
182+
args.Add(packageFolder);
180183
}
184+
185+
additionalProbingPaths = packageFolders;
181186
}
182187

183188
if (File.Exists(runtimeConfig))
184189
{
185190
args.Add("--runtimeconfig");
186191
args.Add(runtimeConfig);
187192
}
188-
else if (startupProject.RuntimeFrameworkVersion!.Length != 0)
193+
else if (!string.IsNullOrEmpty(startupProject.RuntimeFrameworkVersion))
189194
{
190195
args.Add("--fx-version");
191196
args.Add(startupProject.RuntimeFrameworkVersion);
@@ -258,6 +263,13 @@ protected override int Execute(string[] _)
258263
args.Add("--prefix-output");
259264
}
260265

266+
// Only `migrations bundle` understands these (it launches a child ef.dll for DbContext discovery);
267+
// every other ef.dll command rejects unrecognized options.
268+
if (IsMigrationsBundle(commands))
269+
{
270+
args.AddRange(GetBundleHostArgs(depsFile, runtimeConfig, startupProject.RuntimeFrameworkVersion, additionalProbingPaths));
271+
}
272+
261273
if (_applicationArgs!.Any())
262274
{
263275
args.Add("--");
@@ -267,6 +279,49 @@ protected override int Execute(string[] _)
267279
return Exe.Run(executable, args, startupProject.ProjectDir);
268280
}
269281

282+
internal static bool IsMigrationsBundle(IReadOnlyList<string> commands)
283+
=> commands.Count >= 2
284+
&& string.Equals(commands[0], "migrations", StringComparison.OrdinalIgnoreCase)
285+
&& string.Equals(commands[1], "bundle", StringComparison.OrdinalIgnoreCase);
286+
287+
// The startup project's host context, forwarded so `migrations bundle` can launch its out-of-process
288+
// discovery child the same way this tool launched ef.dll. See https://github.com/dotnet/efcore/issues/25555.
289+
internal static IReadOnlyList<string> GetBundleHostArgs(
290+
string depsFile,
291+
string runtimeConfig,
292+
string? runtimeFrameworkVersion,
293+
IReadOnlyList<string> additionalProbingPaths)
294+
{
295+
var args = new List<string>();
296+
297+
if (File.Exists(depsFile))
298+
{
299+
args.Add("--deps-file");
300+
args.Add(depsFile);
301+
}
302+
303+
if (File.Exists(runtimeConfig))
304+
{
305+
args.Add("--runtime-config");
306+
args.Add(runtimeConfig);
307+
}
308+
else if (!string.IsNullOrEmpty(runtimeFrameworkVersion))
309+
{
310+
// Mirrors the host --fx-version so the child can pin the same shared framework when there is
311+
// no runtimeconfig.json.
312+
args.Add("--runtime-framework-version");
313+
args.Add(runtimeFrameworkVersion);
314+
}
315+
316+
foreach (var additionalProbingPath in additionalProbingPaths)
317+
{
318+
args.Add("--additional-probing-path");
319+
args.Add(additionalProbingPath);
320+
}
321+
322+
return args;
323+
}
324+
270325
private static (string, string) ResolveProjects(
271326
string? projectPath,
272327
string? startupProjectPath)

‎src/ef/Commands/MigrationsBundleCommand.Configure.cs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ public override void Configure(CommandLineApplication command)
2222
_selfContained = command.Option("--self-contained", Resources.SelfContainedDescription);
2323
_runtime = command.Option("-r|--target-runtime <RUNTIME_IDENTIFIER>", Resources.MigrationsBundleRuntimeDescription);
2424

25+
ConfigureHostOptions(command);
26+
2527
base.Configure(command);
2628
}
29+
30+
// Implemented in MigrationsBundleCommand.cs, which is only compiled into ef.dll: dotnet-ef also
31+
// compiles this file but must not expose (or swallow) the host options it forwards to ef.dll.
32+
partial void ConfigureHostOptions(CommandLineApplication command);
2733
}

0 commit comments

Comments
 (0)