解读ASP.NET 5 & MVC6系列教程(10):Controller与Action

2019-05-22 14:11:35刘景俊
类,在该类中,设置的必要条件是,定义了MVC的Controller必须要引用了如下程序集中的一个或多个程序集,列表如下:

Microsoft.AspNet.Mvc
Microsoft.AspNet.Mvc.Core
Microsoft.AspNet.Mvc.ModelBinding
Microsoft.AspNet.Mvc.Razor
Microsoft.AspNet.Mvc.Razor.Host
Microsoft.AspNet.Mvc.TagHelpers
Microsoft.AspNet.Mvc.Xml
Microsoft.AspNet.PageExecutionInstrumentation.Interfaces

也就是说,如果你定义了一个引用了Microsoft.AspNet.Mvc的DLL类库的话,其里面的POCO Controller都会被认为是MVC的Controller。换句话说,如果你定义的POCO Controller类没有引用上述程序集中的任意一个程序集,那这些Controller类不会被认为是MVC的Controller。

程序集的查找

目前有两种方式可以自定义Controller的查找机制,第一种是继承IAssemblyProvider实现CandidateAssemblies方法(或重载DefaultAssemblyProvider),来定义自己的逻辑。接口定义如下:

public interface IAssemblyProvider
{
 IEnumerable<Assembly> CandidateAssemblies { get; }
}

另外一种方式,可能相对来说更简单一些,那就是使用IServicesCollection上定义的扩展方法来定义要查找的程序集:

services.AddMvc().WithControllersAsServices(new[]
{
 typeof(MyController).Assembly,
 typeof(ExternalPocoController).Assembly
});

使用上述代码后,系统将会把DefaultAssemblyProvider切换成FixedSetAssemblyProvider来实现上述判断机制,即:在固定范围内的程序集里进行查找。

程序集的筛选

确定了程序集以后,另外一个问题就来了,如何判断一个程序集是否引用了上述MVC必要条件中所列的程序集呢?答案是,Microsoft.Framework.Runtime中的ILibraryManager接口实例的GetReferencingLibraries方法,可以查找有多少个程序集引用了上述列表中的其中一个程序集。例如,可以根据Microsoft.AspNet.Mvc程序集,来查找有多少个程序集引用了该程序集,示例如下:

var col = this.Resolver.GetRequiredService<ILibraryManager>();
var data = col.GetReferencingLibraries("Microsoft.AspNet.Mvc");

该功能在DefaultAssemblyProvider默认实现类中的使用代码如下:

protected virtual IEnumerable<ILibraryInformation> GetCandidateLibraries()
{
 if (ReferenceAssemblies == null)
 {
  return Enumerable.Empty<ILibraryInformation>();
 }

 // GetReferencingLibraries returns the transitive closure of referencing assemblies
 // for a given assembly.
 return ReferenceAssemblies.SelectMany(_libraryManager.GetReferencingLibraries)
        .Distinct()
        .Where(IsCandidateLibrary);
}

Controller的判断

确定了符合必要条件的程序集之后,就可以遍历该程序集内所有的类型,并接着判断该类型是否是Controller了。在新版的Controller判断上,实现该功能的是一个