自从用 dotnet run 成功运行第一个 "Hello world" .NET Core 应用程序后,一直有个好奇心:dotnet run 究竟是如何运行一个 .NET Core 应用程序的?

从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0在Linux上以本地机器码运行 ASP.NET Core 站点 之后,这个好奇心被进一步激发,于是“探秘 dotnet run”顺理成章地成为.NET跨平台之旅的下一站。

首先我们了解一下 dotnet 命令是什么东东?dotnet 命令实际就是一个C#写的简单的.NET控制台程序(详见Program.cs),但为什么在不同操作系统平台上安装 dotnet cli 后,dotnet 命令是一个本地可执行文件?功臣依然是前一篇博文中见识过其威力的 .NET Native,dotnet 命令背后的.NET控制台程序被编译为针对不同操作系统的本地机器码,dotnet 命令本身就是 .NET Native 的一个实际应用。

接下来,我们沿着 dotnet 命令的 Program.cs 探寻 dotnet run 运行 .NET Core 应用程序的秘密。

dotnet Program.cs 的C#代码不超过200行,而与我们的探秘之旅最相关的是下面这一段代码:

var builtIns = new Dictionary<string, Func<string[], int>>
{
//...
["run"] = RunCommand.Run,
//...
}; Func<string[], int> builtIn;
if (builtIns.TryGetValue(command, out builtIn))
{
return builtIn(appArgs.ToArray());
}

从上面的代码可以看出,dotnet run 命令实际执行的是 RunCommand 的 Run() 方法,沿着 Run() 方法往前走,从 Start() 方法 来到 RunExecutable() 方法,此处的风景吸引了我们。

在 RunExecutable() 方法中,先执行了 BuildCommand.Run() 方法 —— 对 .NET Core 应用程序进行 build :

var result = Build.BuildCommand.Run(new[]
{
$"--framework",
$"{_context.TargetFramework}",
$"--configuration",
Configuration,
$"{_context.ProjectFile.ProjectDirectory}"
});

如果 build 成功,会在 .NET Core 应用程序的bin文件夹中生成相应的程序集(.dll文件)。如何 build,不是我们这次旅程所关心的,我们关心的是 build 出来的程序集是如何被运行的。

所以略过此处风景,继续向前,发现了下面的代码:

result = Command.Create(outputName, _args)
.ForwardStdOut()
.ForwardStdErr()
.Execute()
.ExitCode;

从上面的代码可以分析出,dotnet run 最终执行的是一个命令行,而这个命令行是由 Command.Create() 根据 outputName 生成的,outputName 就是 BuildCommand 生成的应用程序的程序集名称。显然,秘密一定藏在 Command.Create() 中。

目标 Command.Create() ,跑步前进 。。。在 Command.cs 中看到了 Command.Create() 的庐山真面目:

public static Command Create(
string commandName,
IEnumerable<string> args,
NuGetFramework framework = null,
string configuration = Constants.DefaultConfiguration)
{
var commandSpec = CommandResolver.TryResolveCommandSpec(commandName,
args,
framework,
configuration: configuration); if (commandSpec == null)
{
throw new CommandUnknownException(commandName);
} var command = new Command(commandSpec); return command;
}

发现 CommandResolver,快步迈入 CommandResolver.TryResolveCommandSpec() ,看看其中又是怎样的风景:

public static CommandSpec TryResolveCommandSpec(
string commandName,
IEnumerable<string> args,
NuGetFramework framework = null,
string configuration=Constants.DefaultConfiguration,
string outputPath=null)
{
var commandResolverArgs = new CommandResolverArguments
{
CommandName = commandName,
CommandArguments = args,
Framework = framework,
ProjectDirectory = Directory.GetCurrentDirectory(),
Configuration = configuration,
OutputPath = outputPath
}; var defaultCommandResolver = DefaultCommandResolverPolicy.Create(); return defaultCommandResolver.Resolve(commandResolverArgs);
}

发现 DefaultCommandResolverPolicy ,一个箭步,置身其 Create() 方法中:

public static CompositeCommandResolver Create()
{
var environment = new EnvironmentProvider();
var packagedCommandSpecFactory = new PackagedCommandSpecFactory(); var platformCommandSpecFactory = default(IPlatformCommandSpecFactory);
if (PlatformServices.Default.Runtime.OperatingSystemPlatform == Platform.Windows)
{
platformCommandSpecFactory = new WindowsExePreferredCommandSpecFactory();
}
else
{
platformCommandSpecFactory = new GenericPlatformCommandSpecFactory();
} return CreateDefaultCommandResolver(environment, packagedCommandSpecFactory, platformCommandSpecFactory);
}

出现两道风景 —— packagedCommandSpecFactory 与 platformCommandSpecFactory,它们都被作为参数传给了 CreateDefaultCommandResolver() 方法。

一心不可二用,先看其中一道风景 —— packagedCommandSpecFactory ,急不可待地奔向 CreateDefaultCommandResolver() 方法 。

public static CompositeCommandResolver CreateDefaultCommandResolver(
IEnvironmentProvider environment,
IPackagedCommandSpecFactory packagedCommandSpecFactory,
IPlatformCommandSpecFactory platformCommandSpecFactory)
{
var compositeCommandResolver = new CompositeCommandResolver();
//..
compositeCommandResolver.AddCommandResolver(
new ProjectToolsCommandResolver(packagedCommandSpecFactory));
//..
return compositeCommandResolver;
}

packagedCommandSpecFactory 将我们引向新的风景 —— ProjectToolsCommandResolver 。飞奔过去之后,立即被 Resolve() 方法吸引(在之前的 DefaultCommandResolverPolicy.Create() 执行之后,执行 defaultCommandResolver.Resolve(commandResolverArgs) 时,该方法被调用)。

这里的风景十八弯。在 ProjectToolsCommandResolver 中七绕八绕,从 ResolveFromProjectTools() -> ResolveCommandSpecFromAllToolLibraries() -> ResolveCommandSpecFromToolLibrary() 。。。又回到了 PackagedCommandSpecFactory ,进入 CreateCommandSpecFromLibrary() 方法。

在 PackagedCommandSpecFactory 中继续转悠,在从 CreateCommandSpecWrappingWithCorehostfDll() 到 CreatePackageCommandSpecUsingCorehost() 时,发现一个新东东从天而降 —— corehost :

private CommandSpec CreatePackageCommandSpecUsingCorehost(
string commandPath,
IEnumerable<string> commandArguments,
string depsFilePath,
CommandResolutionStrategy commandResolutionStrategy)
{
var corehost = CoreHost.HostExePath; var arguments = new List<string>();
arguments.Add(commandPath); if (depsFilePath != null)
{
arguments.Add($"--depsfile:{depsFilePath}");
} arguments.AddRange(commandArguments); return CreateCommandSpec(corehost, arguments, commandResolutionStrategy);
}

这里的 corehost 变量是干嘛的?心中产生了一个大大的问号。

遥望 corehost 的身后,发现 CreateCommandSpec() 方法(corehost 是它的一个参数),一路狂奔过去:

private CommandSpec CreateCommandSpec(
string commandPath,
IEnumerable<string> commandArguments,
CommandResolutionStrategy commandResolutionStrategy)
{
var escapedArgs = ArgumentEscaper.EscapeAndConcatenateArgArrayForProcessStart(commandArguments); return new CommandSpec(commandPath, escapedArgs, commandResolutionStrategy);
}

原来 corehost 是作为 commandPath 的值,也就是说 Command.Create() 创建的 dotnet run 所对应的命令行是以 corehost 开头的,秘密一定就在 corehost 的前方不远处。

corehost 的值来自 CoreHost.HostExePath ,HostExePath 的值来自 Constants.HostExecutableName ,HostExecutableName 的值是:

public static readonly string HostExecutableName = "corehost" + ExeSuffix;

corehost 命令!原来 dotnet run 命令最终执行的 corehost 命令,corehost 才是背后真正的主角,.NET Core 应用程序是由它运行的。

去 dotnet cli 的安装目录一看,果然有一个 corehost 可执行文件。

-rwxr-xr-x  root root  Mar   : /usr/share/dotnet-nightly/bin/corehost

既然 corehost 是主角,那么不通过 dotnet run ,直接用 corehost 应该也可以运行 .NET Core 程序,我们来试一试。

进入示例站点 about.cnblogs.com 的 build 输出文件夹:

cd /git/AboutUs/bin/Debug/netstandardapp1.3/ubuntu.14.04-x64

然后直接用 corehost 命令运行程序集:

/usr/share/dotnet-nightly/bin/corehost AboutUs.dll

运行成功!事实证明 corehost 是运行 .NET Core 程序的主角。

dbug: Microsoft.AspNetCore.Hosting.Internal.WebHost[3]
Hosting starting
dbug: Microsoft.AspNetCore.Hosting.Internal.WebHost[4]
Hosting started
Hosting environment: Production
Application base path: /git/AboutUs/bin/Debug/netstandardapp1.3/ubuntu.14.04-x64
Now listening on: http://*:8001
Application started. Press Ctrl+C to shut down.

去 dotnet cli 的源代码中看一下 corehost 的实现代码,是用 C++ 写的,这是 dotnet cli 中唯一用 C++ 实现的部分,它也不得不用 C++ ,因为它有一个重要职责 —— 加载 coreclr ,再次证实 corehost 是主角。

探秘 dotnet run , 踏破铁鞋,走过千山万水,终于找到了你 —— corehost,终于满足了那颗不安分的好奇心。

.NET跨平台之旅:探秘 dotnet run 如何运行 .NET Core 应用程序的更多相关文章

  1. ASP.NET Core 中文文档 第二章 指南(8) 使用 dotnet watch 开发 ASP.NET Core 应用程序

    原文:Developing ASP.NET Core applications using dotnet watch 作者:Victor Hurdugaci 翻译:谢炀(Kiler) 校对:刘怡(Al ...

  2. 使用 dotnet watch 开发 ASP.NET Core 应用程序

    使用 dotnet watch 开发 ASP.NET Core 应用程序 原文:Developing ASP.NET Core applications using dotnet watch作者:Vi ...

  3. .NET跨平台之旅:将示例站点升级至 .NET Core 1.1 Preview 1

    今天微软发布了 .NET Core 1.1 Preview 1(详见 Announcing .NET Core 1.1 Preview 1 ),紧跟 .NET Core 前进的步伐,我们将示例站点 h ...

  4. DotNet Run 命令介绍

    前言 本篇主要介绍 asp.net core 中,使用 dotnet tools 运行 dotnet run 之后的系统执行过程. 如果你觉得对你有帮助的话,不妨点个[推荐]. 目录 dotnet r ...

  5. dotnet tools 运行 dotnet run

    dotnet tools 运行 dotnet run dotnet run 命令介绍 前言 本篇主要介绍 asp.net core 中,使用 dotnet tools 运行 dotnet run 之后 ...

  6. .NET跨平台之旅:corehost 是如何加载 coreclr 的

    在前一篇博文中,在好奇心的驱使下,探秘了 dotnet run ,发现了神秘的 corehost  —— 运行 .NET Core 应用程序的幕后英雄.有时神秘就是一种诱惑,神秘的 corehost ...

  7. dotnet run是如何启动asp.net core站点的

    在曾经的 asp.net 5 过渡时期,运行 asp.net 5 站点的命令是dnx web:在如今即将到来的 asp.net core 时代,运行 asp.net core 站点的命令是dotnet ...

  8. 【dotnet跨平台】&quot;dotnet restore&quot;和&quot;dotnet run&quot;都做了些什么?

    [dotnet跨平台]"dotnet restore"和"dotnet run"都做了些什么? 前言: 关于dotnet跨平台的相关内容.能够參考:跨平台.NE ...

  9. .NET跨平台之旅:将示例站点从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0

    终于将“.NET跨平台之旅”的示例站点 about.cnblogs.com 从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0 ,经历了不少周折,在这篇博文中记录一下. 从 AS ...

随机推荐

  1. AngularJs学习笔记(制作留言板)

    原文地址:http://www.jmingzi.cn/?post=13 初学Anjularjs两天了,一边学一边写的留言板,只有一级回复嵌套.演示地址 这里总结一下学习的过程和笔记.另外,看看这篇文章 ...

  2. .net程序部署(setupFactory)

    vs 自带的安装打包 实在弱爆了,点都不好用.一直一直在寻觅一个靠谱点的打包工具.在网上寻寻觅觅 寻寻觅觅 功夫不负有心人,终于让我找到了.setupFactory  我用的是 8.0版本 . 首先要 ...

  3. Win10 UWP系列:关于错误 0x80073CF9及一个小bug的解决

    最近一直在开发XX的uwp版本,也是边摸索边做,最近遇到几个比较奇怪的问题,记录于此. 1.项目可用部署到PC,但无法部署到手机,提示以下错误: 错误 : DEP0001 : 意外错误: Instal ...

  4. 设计模式(六)原型模式(Prototype Pattern)

    一.引言 在软件系统中,当创建一个类的实例的过程很昂贵或很复杂,并且我们需要创建多个这样类的实例时,如果我们用new操作符去创建这样的类实例,这未免会增加创建类的复杂度和耗费更多的内存空间,因为这样在 ...

  5. Java-加载数据库驱动,取得数据库连接

    在Java中想要进行数据库操作,最重要的两个步骤就是加载数据驱动,然后取得数据库连接. 1.加载 数据库驱动( Class.forName(String className) ): 因为Java是一种 ...

  6. 如何写出安全的API接口(参数加密+超时处理+私钥验证+Https)- 续(附demo)

    上篇文章说到接口安全的设计思路,如果没有看到上篇博客,建议看完再来看这个. 通过园友们的讨论,以及我自己查了些资料,然后对接口安全做一个相对完善的总结,承诺给大家写个demo,今天一并放出. 对于安全 ...

  7. PowerDesigner从Sqlserver中反转为带注释的字典及快捷键操作

    PowerDesigner的操作经常忘记,所以把常用的功能记录下来备忘. 1.修改反转过来的字段 PowerDesigner从数据库反转的时候,默认不带注释,需要先进行修改. 输入如下脚本: {OWN ...

  8. Maven远程仓库的认证

    大部分远程仓库无须认证就可以访问,但有时处于安全方面的考虑,我们需要提供认证信息才能访问一些远程仓库.为了防止非法的仓库访问,管理员为每个仓库提供了一组用户名及密码. 这时,为了能让Maven访问仓库 ...

  9. OC多态

    要点: 1.多种形态,引用的多种形态对于一个引用变量,可以指向任何类的对象.对于一个父类的引用(类与类之间有一种继承关系),可以指向子类,也可以指向本类,指向的类型不同.当通过此引用向对象发送消息,调 ...

  10. 便于开发的Helper类

    一.将config封装实体层: 例子config: <?xml version="1.0" encoding="utf-8" ?> <Sett ...