相关模块
- AbpAspNetCoreModule
- AbpAspNetCoreMvcModule
- AbpAspNetCoreMvcContractsModule
abp通过这三个模块加载并配置了 asp.net core。,最主要的就是AbpAspNetCoreMvcModule模块类,abp如何基于aspnet core构建自己的控制器和AppServices,就是在这个类中。
-
AbpAspNetCoreMvcModule
将AbpAspNetCoreMvcConventionalRegister类添加到ConventionalRegistrarList列表中,该类主要是用来注入依赖及获取服务生命周期的。public override void PreConfigureServices(ServiceConfigurationContext context) { context.Services.AddConventionalRegistrar(new AbpAspNetCoreMvcConventionalRegistrar()); }
接下来就是重点,在ConfigureServices方法中配置视图和控制器,当然是基于 asp.net core mvc。首先配置Razor:
context.Services.Insert(0, ServiceDescriptor.Singleton<IConfigureOptions<RazorViewEngineOptions>>( new ConfigureOptions<RazorViewEngineOptions>(options => { options.FileProviders.Add( new RazorViewEngineVirtualFileProvider( context.Services.GetSingletonInstance<IObjectAccessor<IServiceProvider>>() ) ); } ) ) );
配置Api描述符:
Configure<ApiDescriptionModelOptions>(options => { options.IgnoredInterfaces.AddIfNotContains(typeof(IAsyncActionFilter)); options.IgnoredInterfaces.AddIfNotContains(typeof(IFilterMetadata)); options.IgnoredInterfaces.AddIfNotContains(typeof(IActionFilter)); });
可以看到 aspnetcore mvc中的过滤器接口,我们将其添加到了Api描述模型选项类中。下面就是注入MVC:
var mvcCoreBuilder = context.Services.AddMvcCore(); var mvcBuilder = context.Services.AddMvc() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => { var resourceType = abpMvcDataAnnotationsLocalizationOptions.AssemblyResources.GetOrDefault(type.Assembly); return factory.Create(resourceType ?? type); }; }) .AddViewLocalization();
使用DI创建控制器,使用的是aspnet core默认的控制器激活器ServiceBasedControllerActivator类:
//Use DI to create controllers context.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
abp提供了一个基于约定的控制器特性提供器类,这个类是基于 aspnetcore mvc的ControllerFeatureProvider构建自己的控制器,并检索判断控制器。
//Add feature providers var partManager = context.Services.GetSingletonInstance<ApplicationPartManager>(); var application = context.Services.GetSingletonInstance<IAbpApplication>(); partManager.FeatureProviders.Add(new AbpConventionalControllerFeatureProvider(application));
该类源码:
public class AbpConventionalControllerFeatureProvider : ControllerFeatureProvider { private readonly IAbpApplication _application; public AbpConventionalControllerFeatureProvider(IAbpApplication application) { _application = application; } protected override bool IsController(TypeInfo typeInfo) { //TODO: Move this to a lazy loaded field for efficiency. if (_application.ServiceProvider == null) { return false; } var configuration = _application.ServiceProvider .GetRequiredService<IOptions<AbpAspNetCoreMvcOptions>>().Value .ConventionalControllers .ConventionalControllerSettings .GetSettingOrNull(typeInfo.AsType()); return configuration != null; } }
由上,abp会基于aspnetcore mvc配置abp的mvc模块,特别是Controller的创建。从代码里面可以看出获取到AbpAspNetCoreMvcOptions的服务再去检索规约的控制器。由此返回是否是控制器。AbpAspNetCoreMvcOptions类是Abp对aspnet core mvc的一个封装,源码如下:
public class AbpAspNetCoreMvcOptions { public ConventionalControllerOptions ConventionalControllers { get; } public AbpAspNetCoreMvcOptions() { ConventionalControllers = new ConventionalControllerOptions(); } } //规约控制器集合 public class ConventionalControllerOptions { public ConventionalControllerSettingList ConventionalControllerSettings { get; } public List<Type> FormBodyBindingIgnoredTypes { get; } public ConventionalControllerOptions() { ConventionalControllerSettings = new ConventionalControllerSettingList(); FormBodyBindingIgnoredTypes = new List<Type> { typeof(IFormFile) }; } public ConventionalControllerOptions Create(Assembly assembly, [CanBeNull] Action<ConventionalControllerSetting> optionsAction = null) { var setting = new ConventionalControllerSetting(assembly, ModuleApiDescriptionModel.DefaultRootPath); // DefaultRootPath = app,abp路由就是以这个app开头的。 optionsAction?.Invoke(setting); setting.Initialize(); ConventionalControllerSettings.Add(setting); return this; } }
AbpAspNetCoreMvcOptions实际上是通过ConventionalControllerOptions来完成规约的配置,来实现自定义的路由以及动态API。
-
AspNetCoreDescriptionModelProvider
abp是如何aspnet core创建自己的API的呢?有这么一个类AspNetCoreDescriptionModelProvider,这个类就是提供了aspnet core的描述模型,源码如下:
public class AspNetCoreApiDescriptionModelProvider : IApiDescriptionModelProvider, ITransientDependency { public ILogger<AspNetCoreApiDescriptionModelProvider> Logger { get; set; } private readonly IApiDescriptionGroupCollectionProvider _descriptionProvider; private readonly AbpAspNetCoreMvcOptions _options; private readonly ApiDescriptionModelOptions _modelOptions; public AspNetCoreApiDescriptionModelProvider( IApiDescriptionGroupCollectionProvider descriptionProvider, IOptions<AbpAspNetCoreMvcOptions> options, IOptions<ApiDescriptionModelOptions> modelOptions) { _descriptionProvider = descriptionProvider; _options = options.Value; _modelOptions = modelOptions.Value; Logger = NullLogger<AspNetCoreApiDescriptionModelProvider>.Instance; } public ApplicationApiDescriptionModel CreateApiModel() { //TODO: Can cache the model? var model = ApplicationApiDescriptionModel.Create(); foreach (var descriptionGroupItem in _descriptionProvider.ApiDescriptionGroups.Items) { foreach (var apiDescription in descriptionGroupItem.Items) { if (!apiDescription.ActionDescriptor.IsControllerAction()) { continue; } AddApiDescriptionToModel(apiDescription, model); } } return model; } private void AddApiDescriptionToModel(ApiDescription apiDescription, ApplicationApiDescriptionModel model) { var controllerType = apiDescription.ActionDescriptor.AsControllerActionDescriptor().ControllerTypeInfo.AsType(); var setting = FindSetting(controllerType); var moduleModel = model.GetOrAddModule(GetRootPath(controllerType, setting)); var controllerModel = moduleModel.GetOrAddController(controllerType.FullName, CalculateControllerName(controllerType, setting), controllerType, _modelOptions.IgnoredInterfaces); var method = apiDescription.ActionDescriptor.GetMethodInfo(); var uniqueMethodName = GetUniqueActionName(method); if (controllerModel.Actions.ContainsKey(uniqueMethodName)) { Logger.LogWarning($"Controller '{controllerModel.ControllerName}' contains more than one action with name '{uniqueMethodName}' for module '{moduleModel.RootPath}'. Ignored: " + method); return; } Logger.LogDebug($"ActionApiDescriptionModel.Create: {controllerModel.ControllerName}.{uniqueMethodName}"); var actionModel = controllerModel.AddAction(uniqueMethodName, ActionApiDescriptionModel.Create( uniqueMethodName, method, apiDescription.RelativePath, apiDescription.HttpMethod, GetSupportedVersions(controllerType, method, setting) )); AddParameterDescriptionsToModel(actionModel, method, apiDescription); } private static string CalculateControllerName(Type controllerType, ConventionalControllerSetting setting) { var controllerName = controllerType.Name.RemovePostFix("Controller").RemovePostFix(ApplicationService.CommonPostfixes); if (setting?.UrlControllerNameNormalizer != null) { controllerName = setting.UrlControllerNameNormalizer(new UrlControllerNameNormalizerContext(setting.RootPath, controllerName)); } return controllerName; } }
这个类为我们提供了从Action到Controller的描述,构建了abp自己的api。它的调用有两个地方,一个是AbpApiDefinitionController,一个是ProxyScriptManager,前者是定义Abp的api控制器定义的地方,后者则是生成代理脚本的地方,abp的示例项目BookStore中会调用接口Abp/ServiceProxyScript生成一个js文件,这个js文件里面就是api的url地址,前端通过访问这个api地址来访问appservice等后端方法。源码如下:
[Area("Abp")] [Route("Abp/ServiceProxyScript")] [DisableAuditing] public class AbpServiceProxyScriptController : AbpController { private readonly IProxyScriptManager _proxyScriptManager; public AbpServiceProxyScriptController(IProxyScriptManager proxyScriptManager) { _proxyScriptManager = proxyScriptManager; } [HttpGet] [Produces("text/javascript", "text/plain")] public string GetAll(ServiceProxyGenerationModel model) { model.Normalize(); return _proxyScriptManager.GetScript(model.CreateOptions()); } }
-
AbpHttpModule模块
Abp创建jquery代理脚本生成器,主要用来生产api提供给前端访问public override void ConfigureServices(ServiceConfigurationContext context) { Configure<AbpApiProxyScriptingOptions>(options => { options.Generators[JQueryProxyScriptGenerator.Name] = typeof(JQueryProxyScriptGenerator); }); }