剖析ASP.NET Core MVC(Part 1)- AddMvcCore(译)
原文:https://www.stevejgordon.co.uk/asp-net-core-mvc-anatomy-addmvccore
发布于:2017年3月
环境:ASP.NET Core 1.1
欢迎阅读新系列的第一部分,我将剖析MVC源代码,给大家展示隐藏在表面之下的工作机制。此系列将分析MVC的内部,如果觉得枯燥,可以停止阅读。但就我个人而言,也是经过反复阅读、调试甚至抓狂,直到最后理解ASP.NET MVC源代码(或者自认为理解),从中获益匪浅。通过了解框架的运作机制,我们可以更好的使用它们,更容易解决遇到的问题。
我会尽力给大家解释对源码的理解,我不能保证自己的理解和解释是100%正确,但我会竭尽所能。要知道简洁清晰的把一段代码解释清楚是很困难的,我将通过小块代码展示MVC源代码,并附源文件链接,方便大家追踪。阅读之后如果仍不理解,我建议你花些时间读读源代码,必要时亲自动手调试一下。我希望此系列会引起像我一样喜欢刨根问底的人的兴趣。
AddMvcCore
本文我将剖析AddMvcCore到底为我们做了什么,同时关注几个像 ApplicationPartManager这样的类。本文使用的project.json基于rel/1.1.2源代码,通过运行MVC Sandbox 项目进行调试。
| 注:MvcSandbox为ASP.Net Core MVC源码中的示列项目。 |
由于版本在不断更新,一些类和方法可能会改变,尤其是内部。请始终参考GitHub上的最新代码。对于MvcSandbox ConfigureServices我已作更新:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}
AddMvcCore是IServiceCollection的扩展方法。通常把一组关联的服务注册到服务集合(services collection)时都使用扩展方法这种模式。在构建MVC应用时,有两个扩展方法用来注册MVC服务(MVC Services),AddMvcCore是其中之一。相对AddMvc方法,AddMvcCore提供较少的服务子集。一些不需要使用MVC所有特性的简单程序,就可以使用AddMvcCore。比如在构建REST APIs,就不需要Razor相关组件,我一般使用AddMvcCore。你也可以在AddMvcCore之后手动添加额外的服务,或者直接使用功能更多的AddMvc。AddMvcCore的实现:
public static IMvcCoreBuilder AddMvcCore(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
} var partManager = GetApplicationPartManager(services);
services.TryAddSingleton(partManager); ConfigureDefaultFeatureProviders(partManager);
ConfigureDefaultServices(services);
AddMvcCoreServices(services); var builder = new MvcCoreBuilder(services, partManager); return builder;
}
AddMvcCore做的第一件事就是通过GetApplicationPartManager静态方法获得ApplicationPartManager,把IServiceCollection作为参数传递给GetApplicationPartManager。
GetApplicationPartManager的实现:
private static ApplicationPartManager GetApplicationPartManager(IServiceCollection services)
{
var manager = GetServiceFromCollection<ApplicationPartManager>(services);
if (manager == null)
{
manager = new ApplicationPartManager(); var environment = GetServiceFromCollection<IHostingEnvironment>(services);
if (string.IsNullOrEmpty(environment?.ApplicationName))
{
return manager;
} var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(environment.ApplicationName);
foreach (var part in parts)
{
manager.ApplicationParts.Add(part);
}
} return manager;
}
本方法首先检查当前已注册的服务中是否有ApplicationPartManager,通常情况是没有的,但极少情况你可能在调用AddMvcCore之前注册了其它服务。ApplicationPartManager如果不存在则创建一个新的。
接下来的代码是计算ApplicationPartManager的ApplicationParts属性值。首先从服务集合(services collection)中获得IHostingEnvironment。如果能够获IHostingEnvironment实例,则通过它获得程序名或封装名(application/assem bly name),然后传递给静态方法DefaultAssemblyPartDiscoveryProvider,DiscoverAssemblyParts方法将返回IEnumerable<ApplicationPart>。
public static IEnumerable<ApplicationPart> DiscoverAssemblyParts(string entryPointAssemblyName)
{
var entryAssembly = Assembly.Load(new AssemblyName(entryPointAssemblyName));
var context = DependencyContext.Load(Assembly.Load(new AssemblyName(entryPointAssemblyName))); return GetCandidateAssemblies(entryAssembly, context).Select(p => new AssemblyPart(p));
}
DiscoverAssemblyParts 首先通过封装名(assembly name)获得封装对象(Assembly Object)和DependencyContex。本例封装名为“MvcSandbox”。然后将这些值传递给GetCandidateAssemblies方法,GetCandidateAssemblies再调用GetCandidateLibraries方法。
internal static IEnumerable<Assembly> GetCandidateAssemblies(Assembly entryAssembly, DependencyContext dependencyContext)
{
if (dependencyContext == null)
{
// Use the entry assembly as the sole candidate.
return new[] { entryAssembly };
} return GetCandidateLibraries(dependencyContext)
.SelectMany(library => library.GetDefaultAssemblyNames(dependencyContext))
.Select(Assembly.Load);
} internal static IEnumerable<RuntimeLibrary> GetCandidateLibraries(DependencyContext dependencyContext)
{
if (ReferenceAssemblies == null)
{
return Enumerable.Empty<RuntimeLibrary>();
} var candidatesResolver = new CandidateResolver(dependencyContext.RuntimeLibraries, ReferenceAssemblies);
return candidatesResolver.GetCandidates();
}
解释一下GetCandidateLibraries做了什么:
它返回一个在<see cref=”ReferenceAssemblies”/>中引用的程序集列表,默认是我们引用的主要MVC程序集,不包含项目本身的程序集。
更明确一些,获得的程序集列表包含了我们的解决方案中引用的所有MVC程序集。
ReferenceAssemblies是一个定义在DefaultAssemblyPartDiscoveryProvider类中静态HashSet<string>,它包含13个MVC默认的程序集。
internal static HashSet<string> ReferenceAssemblies { get; } = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"Microsoft.AspNetCore.Mvc",
"Microsoft.AspNetCore.Mvc.Abstractions",
"Microsoft.AspNetCore.Mvc.ApiExplorer",
"Microsoft.AspNetCore.Mvc.Core",
"Microsoft.AspNetCore.Mvc.Cors",
"Microsoft.AspNetCore.Mvc.DataAnnotations",
"Microsoft.AspNetCore.Mvc.Formatters.Json",
"Microsoft.AspNetCore.Mvc.Formatters.Xml",
"Microsoft.AspNetCore.Mvc.Localization",
"Microsoft.AspNetCore.Mvc.Razor",
"Microsoft.AspNetCore.Mvc.Razor.Host",
"Microsoft.AspNetCore.Mvc.TagHelpers",
"Microsoft.AspNetCore.Mvc.ViewFeatures"
};
GetCandidateLibraries使用CandidateResolver类定位并返回“候选人”。CandidateResolver 通过运行时对象(RuntimeLibrary objects)和ReferenceAssemblies构造。每个运行时对象依次迭代并添加到一个字典中,添加过程中检查依赖名(dependency name)是否唯一,如果不唯一则抛出异常。
public CandidateResolver(IReadOnlyList<RuntimeLibrary> dependencies, ISet<string> referenceAssemblies)
{
var dependenciesWithNoDuplicates = new Dictionary<string, Dependency>(StringComparer.OrdinalIgnoreCase);
foreach (var dependency in dependencies)
{
if (dependenciesWithNoDuplicates.ContainsKey(dependency.Name))
{
throw new InvalidOperationException(Resources.FormatCandidateResolver_DifferentCasedReference(dependency.Name));
}
dependenciesWithNoDuplicates.Add(dependency.Name, CreateDependency(dependency, referenceAssemblies));
} _dependencies = dependenciesWithNoDuplicates;
}
每个依赖对象(既RuntimeLibrary)都作为新的依赖对象存储到字典中。这些对象包含一个DependencyClassification属性,用来筛选需要的libraries (candidates)。DependencyClassification是一个枚举类型:
private enum DependencyClassification
{
Unknown = ,
Candidate = ,
NotCandidate = ,
MvcReference =
}
创建Dependency的时候,如果与ReferenceAssemblies HashSet匹配,则标记为MvcReference,其余标记为Unknown。
private Dependency CreateDependency(RuntimeLibrary library, ISet<string> referenceAssemblies)
{
var classification = DependencyClassification.Unknown;
if (referenceAssemblies.Contains(library.Name))
{
classification = DependencyClassification.MvcReference;
} return new Dependency(library, classification);
}
当CandidateResolver.GetCandidates方法被调用时,结合ComputeClassification方法,遍历整个依赖对象树。每个依赖对象都将检查他的所有子项,直到匹配Candidate或者MvcReference,同时标记父依赖项为Candidate类型。遍历结束将返回包含identified candidates的IEnumerable<RuntimeLibrary>。例如本例,只有MvcSandbox程序集被标记为Candidate。
public IEnumerable<RuntimeLibrary> GetCandidates()
{
foreach (var dependency in _dependencies)
{
if (ComputeClassification(dependency.Key) == DependencyClassification.Candidate)
{
yield return dependency.Value.Library;
}
}
} private DependencyClassification ComputeClassification(string dependency)
{
Debug.Assert(_dependencies.ContainsKey(dependency)); var candidateEntry = _dependencies[dependency];
if (candidateEntry.Classification != DependencyClassification.Unknown)
{
return candidateEntry.Classification;
}
else
{
var classification = DependencyClassification.NotCandidate;
foreach (var candidateDependency in candidateEntry.Library.Dependencies)
{
var dependencyClassification = ComputeClassification(candidateDependency.Name);
if (dependencyClassification == DependencyClassification.Candidate ||
dependencyClassification == DependencyClassification.MvcReference)
{
classification = DependencyClassification.Candidate;
break;
}
} candidateEntry.Classification = classification; return classification;
}
}
DiscoverAssemblyParts将返回的candidates转换为新的AssemblyPart。此对象是对程序集的简单封装,只包含了如名称、类型等主要封装属性。后续我可能单独撰文分析此类。
最后,通过GetApplicationPartManager,AssemblyParts被加入到ApplicationPartManager。
var parts = DefaultAssemblyPartDiscoveryProvider.DiscoverAssemblyParts(environment.ApplicationName);
foreach (var part in parts)
{
manager.ApplicationParts.Add(part);
}
} return manager;
返回的ApplicationPartManager实例通过AddMvcCore扩展方法加入到services collection。
接下来AddMvcCore把ApplicationPartManager作为参数调用静态ConfigureDefaultFeatureProviders方法,为ApplicationPartManager的FeatureProviders添加ControllerFeatureProvider。
private static void ConfigureDefaultFeatureProviders(ApplicationPartManager manager)
{
if (!manager.FeatureProviders.OfType<ControllerFeatureProvider>().Any())
{
manager.FeatureProviders.Add(new ControllerFeatureProvider());
}
}
ControllerFeatureProvider将被用在ApplicationPar的实例中发现controllers。我将在后续的博文中介绍ControllerFeatureProvider。现在我们继续研究AddMovCore的最后一步。(ApplicationPartManager此时已更新)
首先调用私有方法ConfigureDefaultServices,通过Microsoft.AspNetCore.Routing提供的AddRouting扩展方法开启routing功能。它提供启用routing功能所需的必要服务和配置。本文不对此作详细描述。
AddMvcCore接下来调用另一个私有方法AddMvcCoreServices,该方法负责注册MVC核心服务,包括框架可选项,action 的发现、选择和调用,controller工厂,模型绑定和认证。
最后AddMvcCore通过services collection和ApplicationPartManager,构造一个新的MvcCoreBuilder对象。此类被叫做:
允许细粒度的配置MVC基础服务(Allows fine grained configuration of essential MVC services.)
AddMvcCore扩展方法返回MvcCoreBuilder,MvcCoreBuilder包含IserviceCollection和ApplicationPartManager属性。MvcCoreBuilder和其扩展方法用在AddMvcCore初始化之后做一些额外的配置。实际上,AddMvc方法中首先调用的是AddMvcCore,然后使用MvcCoreBuilder配置额外的服务。
小结
要把上述所有问题都解释清楚不是件容易的事,所以简单总结一下。本文我们分析的是MVC底层代码,主要实现了把MVCs需要的服务添加到IserviceCollection中。通过追踪ApplicationPartManager的创建过程,我们了解了MVC如何一步步创建内部应用模型(ApplicationModel)。虽然我们并没有看到很多实际的功能,但通过对startup的跟踪分析我们发现了许多有趣的东西,这为后续分析奠定了基础。
以上就是我对AddMvcCore的初步探究,共有46个附加项注册到IservceCollection中。下一篇我将进一步分析AddMvc扩展方法。
剖析ASP.NET Core MVC(Part 1)- AddMvcCore(译)的更多相关文章
- asp.net core mvc剖析:启动流程
asp.net core mvc是微软开源的跨平台的mvc框架,首先它跟原有的MVC相比,最大的不同就是跨平台,然后又增加了一些非常实用的新功能,比如taghelper,viewcomponent,D ...
- 剖析ASP.NET Core(Part 2)- AddMvc(译)
原文:https://www.stevejgordon.co.uk/asp-net-core-mvc-anatomy-addmvccore发布于:2017年3月环境:ASP.NET Core 1.1 ...
- ASP.NET Core MVC 源码学习:MVC 启动流程详解
前言 在 上一篇 文章中,我们学习了 ASP.NET Core MVC 的路由模块,那么在本篇文章中,主要是对 ASP.NET Core MVC 启动流程的一个学习. ASP.NET Core 是新一 ...
- 在ASP.NET Core MVC中构建简单 Web Api
Getting Started 在 ASP.NET Core MVC 框架中,ASP.NET 团队为我们提供了一整套的用于构建一个 Web 中的各种部分所需的套件,那么有些时候我们只需要做一个简单的 ...
- Bare metal APIs with ASP.NET Core MVC(转)
ASP.NET Core MVC now provides a true "one asp.net" framework that can be used for building ...
- 扒一扒asp.net core mvc控制器的寻找流程
不太会排版,大家将就看吧. asp.net core mvc和asp.net mvc中都有一个比较有意思的而又被大家容易忽略的功能,控制器可以写在非Web程序集中,比如Web程序集:"MyW ...
- 《精通 ASP.NET Core MVC (第七版)》开始发售
学习 Web 开发技术很难吗?没有适合的学习资料,确实很枯燥,很难.如果有一本如同良师益友的优秀图书辅助,就很轻松,一点也不难! 对于优秀的技术图书来说,必须从读者的角度来编写,而不是从作者的角度来编 ...
- ASP.NET Core MVC/WebAPi 模型绑定探索
前言 相信一直关注我的园友都知道,我写的博文都没有特别枯燥理论性的东西,主要是当每开启一门新的技术之旅时,刚开始就直接去看底层实现原理,第一会感觉索然无味,第二也不明白到底为何要这样做,所以只有当你用 ...
- ASP.NET Core MVC 配置全局路由前缀
前言 大家好,今天给大家介绍一个 ASP.NET Core MVC 的一个新特性,给全局路由添加统一前缀.严格说其实不算是新特性,不过是Core MVC特有的. 应用背景 不知道大家在做 Web Ap ...
随机推荐
- java的关键字final
final可以修饰类,成员方法,成员变量. 1.final修饰的类不能被继承,所以没有子类 final class First{ int num; } class Second extends Fir ...
- java中的i++与++i有什么区别?
刚开始接触时,做了一些小测试,还以为这两个没有什么区别. public class OperatorDemo { public static void main(String[] args){ int ...
- [PAT] 1147 Heaps(30 分)
1147 Heaps(30 分) In computer science, a heap is a specialized tree-based data structure that satisfi ...
- Python+Selenium 自动化实现实例-获取页面元素信息(百度首页)
#coding=utf-8from selenium import webdriverdriver = webdriver.Chrome()driver.get("http://www.ba ...
- matlab基本指令
基本命令 close all //关闭所有figure 命令打开的窗口,在命令窗口输入 clear all //清除之前运行程序所存下的所有变量 size(mat) a = [1 2 3 ; 4 5 ...
- Centos7使用squid实现正向代理
正向代理:代理服务器帮助客户端(浏览器)实现互联网的访问 (1)代理服务器配置 1.安装squid yum install squid -y 2.编辑squid配置文件 #vim /etc/squid ...
- Intellij IDEA 去掉Mapper文件中的背景
1.在setting中输入:inspection --> SQL 2.去掉背景颜色,Apply即可
- NYOJ 228 士兵杀敌(五)【差分标记裸题】
题目链接 所有元素初始值为0才能这么做: ①l--r全加1 a[l]++; a[r+1]--; 求一遍前缀和为元素本身. 求两遍前缀和为元素前缀和. #include<cstdio> #i ...
- 洛谷P3391文艺平衡树(Splay)
题目传送门 转载自https://www.cnblogs.com/yousiki/p/6147455.html,转载请注明出处 经典引文 空间效率:O(n) 时间效率:O(log n)插入.查找.删除 ...
- Single Number III(LintCode)
Single Number III Given 2*n + 2 numbers, every numbers occurs twice except two, find them. Example G ...