在分析Orchard的模块加载之前,先简要说一下因为Orchard中的模块并不是都被根(启动)项目所引用的,所以当Orchard需要加载一个模块时首先需要保证该模块所依赖的其它程序集能够被找到,那么才能正确的加载一个模块。在上一篇文章中对Orchard如何通过Module.txt以及Theme.txt完成对相应模块、引用依赖的分析和探测工作,并最后生成一个ExtensionLoadingContext,其主要包含了模块程序集路径以及其依赖路径等等详细信息。
  在Orchard官方文档中提到"~/App_Data/Dependencies"目录,说它是一个在传统的bin目录之外ASP.NET用来查找附加程序集的目录,而Orchard就是将拓展模块及其依赖复制到这个目录,然后完成模块程序集加载工作的,"~/App_Data/Dependencies"目录是通过在根项目的web.config中加入以下节点实现的:
     <runtime>
...
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="App_Data/Dependencies" />
...
</assemblyBinding>
</runtime>
  所以简单的来说Orchard后续的处理工作就是,将它们拓展及其引用经过一系列的处理后(如版本问题),通过它们的路径直接复制到App_Data/Dependencies目录下,然后进行加载工作。接下来就对这一过程进行详细分析。  
  以下代码位于ExtensionLoaderCoordinator的SetupExtensions方法中,它的作用就是根据已有的ExtensionLoadingContext去处理可用的拓展。

            // For all existing extensions in the site, ask each loader if they can
// load that extension.
foreach (var extension in context.AvailableExtensions) {
ProcessExtension(context, extension);
}

它的处理过程如下:

先放上全量代码:

         private void ProcessExtension(ExtensionLoadingContext context, ExtensionDescriptor extension) {
var extensionProbes = context.AvailableExtensionsProbes.ContainsKey(extension.Id) ?
context.AvailableExtensionsProbes[extension.Id] :
Enumerable.Empty<ExtensionProbeEntry>();
// materializes the list
extensionProbes = extensionProbes.ToArray(); if (Logger.IsEnabled(LogLevel.Debug)) {
Logger.Debug("Loaders for extension \"{0}\": ", extension.Id);
foreach (var probe in extensionProbes) {
Logger.Debug(" Loader: {0}", probe.Loader.Name);
Logger.Debug(" VirtualPath: {0}", probe.VirtualPath);
Logger.Debug(" VirtualPathDependencies: {0}", string.Join(", ", probe.VirtualPathDependencies));
}
} var moduleReferences =
context.AvailableExtensions
.Where(e =>
context.ReferencesByModule.ContainsKey(extension.Id) &&
context.ReferencesByModule[extension.Id].Any(r => StringComparer.OrdinalIgnoreCase.Equals(e.Id, r.Name)))
.ToList(); var processedModuleReferences =
moduleReferences
.Where(e => context.ProcessedExtensions.ContainsKey(e.Id))
.Select(e => context.ProcessedExtensions[e.Id])
.ToList(); var activatedExtension = extensionProbes.FirstOrDefault(
e => e.Loader.IsCompatibleWithModuleReferences(extension, processedModuleReferences)
); var previousDependency = context.PreviousDependencies.FirstOrDefault(
d => StringComparer.OrdinalIgnoreCase.Equals(d.Name, extension.Id)
); if (activatedExtension == null) {
Logger.Warning("No loader found for extension \"{0}\"!", extension.Id);
} var references = ProcessExtensionReferences(context, activatedExtension); foreach (var loader in _loaders) {
if (activatedExtension != null && activatedExtension.Loader.Name == loader.Name) {
Logger.Information("Activating extension \"{0}\" with loader \"{1}\"", activatedExtension.Descriptor.Id, loader.Name);
loader.ExtensionActivated(context, extension);
}
else if (previousDependency != null && previousDependency.LoaderName == loader.Name) {
Logger.Information("Deactivating extension \"{0}\" from loader \"{1}\"", previousDependency.Name, loader.Name);
loader.ExtensionDeactivated(context, extension);
}
} if (activatedExtension != null) {
context.NewDependencies.Add(new DependencyDescriptor {
Name = extension.Id,
LoaderName = activatedExtension.Loader.Name,
VirtualPath = activatedExtension.VirtualPath,
References = references
});
} // Keep track of which loader we use for every extension
// This will be needed for processing references from other dependent extensions
context.ProcessedExtensions.Add(extension.Id, activatedExtension);
}
根据拓展信息获取相应的探测信息:

         var extensionProbes = context.AvailableExtensionsProbes.ContainsKey(extension.Id) ?
context.AvailableExtensionsProbes[extension.Id] :
Enumerable.Empty<ExtensionProbeEntry>(); // materializes the list
extensionProbes = extensionProbes.ToArray();

  一般来说只有~\Modules和自定义的拓展模块目录下的拓展模块会存在多个探测信息,因为它们被预编译加载器和动态编译加载器同时探测到(bin目录和csproj文件)。

处理模块引用(模块引用模块):

  遍历所有的拓展模块,查找是否依赖于其它模块,如果存在依赖,那么查看所存在的依赖是否已经被处理。
        var moduleReferences =
context.AvailableExtensions
.Where(e =>
context.ReferencesByModule.ContainsKey(extension.Id) &&
context.ReferencesByModule[extension.Id].Any(r => StringComparer.OrdinalIgnoreCase.Equals(e.Id, r.Name)))
.ToList(); var processedModuleReferences =
moduleReferences
.Where(e => context.ProcessedExtensions.ContainsKey(e.Id))
.Select(e => context.ProcessedExtensions[e.Id])
.ToList();
  如果对应依赖的模块已经被处理那么就根据被处理的模块来决定使用哪一个探测实体,因为探测实体的Loader不一样,从而可能与已经处理的模块不兼容,所以ExtensionProbes之前已经通过优先级和最新修改时间进行过排序,而判断是否兼容就是根据这个顺序依次选择优先级最高且兼容的探测信息(注:所有的Loader中,只有预编译加载器不兼容动态编译加载器(看Loader的IsCompatibleWithModuleReferences方法),其余都兼容。所以换句话来说只有一些模块被确定使用动态编译加载器时,后续依赖它的模块的使用预编译加载器的探测信息不会被使用,会转向优先级较低的其它加载器)
        var activatedExtension = extensionProbes.FirstOrDefault(
e => e.Loader.IsCompatibleWithModuleReferences(extension, processedModuleReferences)
);
找出是否被上一次运行的依赖信息:

        var previousDependency = context.PreviousDependencies.FirstOrDefault(
d => StringComparer.OrdinalIgnoreCase.Equals(d.Name, extension.Id)
);

处理引用:

step 1. 获取所有依赖的名称:

       var referenceNames =     (context.ReferencesByModule.ContainsKey(activatedExtension.Descriptor.Id) ?
context.ReferencesByModule[activatedExtension.Descriptor.Id] :
Enumerable.Empty<ExtensionReferenceProbeEntry>())
.Select(r => r.Name)
.Distinct(StringComparer.OrdinalIgnoreCase);
step 2. 遍历并根据名称处理所有依赖(选取最适合的引用):
  1. 判断依赖是否是已处理模块,如果是添加DependencyReferenceDescriptor并返回。
  2. 如果不是已处理模块,则继续判断依赖是否存在于根项目的bin目录下,如果存在直接返回。
  3. 如果以上条件均不符合,则在context.ReferencesByName中根据名称查找,然后根据最新修改时间排序,选择最新的引用文件,如果context.ProcessedReferences不存在该引用,那么将其添加到context.ProcessedReferences中,并调用ReferenceActivated方法。最后添加DependencyReferenceDescriptor并返回。  

      public override void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) {
if (string.IsNullOrEmpty(referenceEntry.VirtualPath))
return; string sourceFileName = _virtualPathProvider.MapPath(referenceEntry.VirtualPath); // Copy the assembly if it doesn't exist or if it is older than the source file.
bool copyAssembly =
!_assemblyProbingFolder.AssemblyExists(referenceEntry.Name) ||
File.GetLastWriteTimeUtc(sourceFileName) > _assemblyProbingFolder.GetAssemblyDateTimeUtc(referenceEntry.Name); if (copyAssembly) {
context.CopyActions.Add(() => _assemblyProbingFolder.StoreAssembly(referenceEntry.Name, sourceFileName)); // We need to restart the appDomain if the assembly is loaded
if (_hostEnvironment.IsAssemblyLoaded(referenceEntry.Name)) {
Logger.Information("ReferenceActivated: Reference \"{0}\" is activated with newer file and its assembly is loaded, forcing AppDomain restart", referenceEntry.Name);
context.RestartAppDomain = true;
}
}
}
注:引用的处理实际上是对预编译和动态编译加载器探测到的模块进行处理,因为其它模块都是被根项目引用的,一旦编译根项目,所有被引用的项目均会被自动编译并将结果放置到bin目录下,而预编译和动态编译加载器则需要通过ReferenceActivated方法,将一个把程序集复制到App_Data/Dependencies目录下的方法添加到context.CopyActions中。
 
处理拓展模块:

     foreach (var loader in _loaders) {
if (activatedExtension != null && activatedExtension.Loader.Name == loader.Name) {
Logger.Information("Activating extension \"{0}\" with loader \"{1}\"", activatedExtension.Descriptor.Id, loader.Name);
loader.ExtensionActivated(context, extension);
}
else if (previousDependency != null && previousDependency.LoaderName == loader.Name) {
Logger.Information("Deactivating extension \"{0}\" from loader \"{1}\"", previousDependency.Name, loader.Name);
loader.ExtensionDeactivated(context, extension);
}
} if (activatedExtension != null) {
context.NewDependencies.Add(new DependencyDescriptor {
Name = extension.Id,
LoaderName = activatedExtension.Loader.Name,
VirtualPath = activatedExtension.VirtualPath,
References = references
});
} // Keep track of which loader we use for every extension
// This will be needed for processing references from other dependent extensions
context.ProcessedExtensions.Add(extension.Id, activatedExtension);
  根据上面代码可以看到处理模块的步骤主要是遍历所有的Loader,然后通过activatedExtension和previousDependency进行匹配,然后对相应的模块进行激活和禁用操作(这里要注意的是如果它们Loader一致,那么只需要调用ExtensionActivated方法即可,否则activatedExtension对应的loader调用activatedExtension,previousDependency调用ExtensionDeactivated禁用之前的同名模块)。最后创建DependencyDescriptor,并将对应的拓展放到ProcessedExtensions中,以供后续模块判断是否引用了已经被处理的模块。
  
  

ExtensionActivated:拓展的激活仅仅是针对预编译和动态编译加载器,其中预编译的激活是将一个复制程序集的方法添加到ctx.CopyActions中和处理引用的方法一致,而动态编译的则仅仅是添加了一个是否需要重启应用域的判断。  

     public override void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
if (_reloadWorkaround.AppDomainRestartNeeded) {
Logger.Information("ExtensionActivated: Module \"{0}\" has changed, forcing AppDomain restart", extension.Id);
ctx.RestartAppDomain = _reloadWorkaround.AppDomainRestartNeeded;
}
}
ExtensionDeactivated:是针对预编译和引用加载器,将一个把原有拓展程序集删除的方法添加到ctx.DeleteActions中。
  预编译: 

         public override void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
if (_assemblyProbingFolder.AssemblyExists(extension.Id)) {
ctx.DeleteActions.Add(
() => {
Logger.Information("ExtensionDeactivated: Deleting assembly \"{0}\" from probing directory", extension.Id);
_assemblyProbingFolder.DeleteAssembly(extension.Id);
}); // We need to restart the appDomain if the assembly is loaded
if (_hostEnvironment.IsAssemblyLoaded(extension.Id)) {
Logger.Information("ExtensionDeactivated: Module \"{0}\" is deactivated and its assembly is loaded, forcing AppDomain restart", extension.Id);
ctx.RestartAppDomain = true;
}
}
}

  引用:

         private void DeleteAssembly(ExtensionLoadingContext ctx, string moduleName) {
var assemblyPath = _virtualPathProvider.Combine("~/bin", moduleName + ".dll");
if (_virtualPathProvider.FileExists(assemblyPath)) {
ctx.DeleteActions.Add(
() => {
Logger.Information("ExtensionRemoved: Deleting assembly \"{0}\" from bin directory (AppDomain will restart)", moduleName);
File.Delete(_virtualPathProvider.MapPath(assemblyPath));
});
ctx.RestartAppDomain = true;
}
}
执行复制和删除命令:
  上面的代码分析可以看到,当激活或禁用一个引用或者模块时,特殊的模块加载器会将一个复制程序集或删除程序集的方法添加到ExtensionLoadingContext中对应的DeleteActions和CopyActions中,而ProcessContextCommands方法就是去处理这些Action。
     private void ProcessContextCommands(ExtensionLoadingContext ctx) {
Logger.Information("Executing list of operations needed for loading extensions...");
foreach (var action in ctx.DeleteActions) {
action();
} foreach (var action in ctx.CopyActions) {
action();
}
}
保存依赖信息:将解析后的DependencyDescriptor存放至对应的xml文件中:
        // And finally save the new entries in the dependencies folder
_dependenciesFolder.StoreDescriptors(context.NewDependencies);
_extensionDependenciesManager.StoreDependencies(context.NewDependencies, desc => GetExtensionHash(context, desc));
 
应用域的重启:如果最后需要重启应用域,那么通过DefaultHostEnvironment的RestartAppDomain方法,通过在bin目录修改marker.txt文件或修改web.config的方法实现应用自动重启的功能。(一般在引用被覆盖和动态编译加载器监控到文件发生变化时需要重启)。
 
上面的分析完成了Orchard整个拓展和依赖的处理过程。
小结:
  Orchard拓展和依赖的处理过程是用于保证所有的拓展模块程序集及其依赖程序集文件都存在于App_Data/Dependencies目录下(其中Core和reference类型的拓展模块已经在根项目的bin目录中无需进行额外处理),如果出现引用程序集被覆盖的情况则需要重启应用域。
  整个处理过程主要是针对没有被依赖的,放置在Modules目录下的拓展模块。因为其余模块都被根项目引用,所以在根项目编译时它们的依赖及模块程序集已经会被自动处理了。

最新文章

  1. JavaScript必须了解的知识点总结。
  2. BurpSuite的使用总结
  3. Android 系统架构
  4. C# 控制台程序 托盘图标 事件响应
  5. java web mvc思想介绍
  6. 基于visual Studio2013解决面试题之0908最大连续数字串
  7. HDU 1754 线段树 单点跟新 HDU 1166 敌兵布阵 线段树 区间求和
  8. 前端js之JavaScript
  9. UVA - 658 最短路
  10. OAF更改动态头行
  11. jQuery获取或设置元素的宽度和高度
  12. 如何使用yql实现跨域访问
  13. python之内置函数(二)与匿名函数、递归函数初识
  14. [转载]PowerDesigner生成的ORACLE 建表脚本中去掉对象的双引号,设置大、小写
  15. oracle第一天笔记
  16. 大数据系列之并行计算引擎Spark部署及应用
  17. Scala从零開始:使用Intellij IDEA写hello world
  18. Linux定时器工具
  19. jquery绑定事件的坑,重复绑定问题
  20. mysql 权限管理 对所有库 所有表 授权 *.*

热门文章

  1. 全网最全最详细的Windows下安装Anaconda2 / Anaconda3(图文详解)
  2. Jenkins问题记录:android构建时提示Unzipping /home/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9/gradle-3.3-all.zip to /home/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9 Except
  3. 从session原理出发解决微信小程序的登陆问题
  4. ClickHouse之clickhouse-local
  5. DynamicProxy系列目录
  6. 基于jQuery消息提示框插件Tipso
  7. Linux命令-用户及权限管理
  8. 在Fragment中保存WebView状态
  9. WPF TextBlock IsTextTrimmed 判断文本是否超出
  10. 推送GitHub报错 fatal: Out of memory, malloc failed 解决办法