剖析ASP.NET Core MVC(Part 1)- AddMvcCore(譯)

來源:互聯網
上載者:User

標籤:個人   基礎   ict   有趣   服務集   Object Storage Service   assembly   不包含   .net   

原文: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)都作為新的依賴Object Storage Service到字典中。這些對象包含一個DependencyClassification屬性,用來篩選需要的libraries (candidates)。DependencyClassification是一個枚舉類型:

private enum DependencyClassification{    Unknown = 0,    Candidate = 1,    NotCandidate = 2,    MvcReference = 3}

建立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(譯)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.