.NET Core開發日誌——Controller

在理清路由的工做流程後,接下來須要考慮的,是MVC框架如何生成Controller以及它的生成時機。html

根據之前ASP.NET MVC的經驗,Controller應該是由一個ControllerFactory構建的。查看ASP.NET Core MVC的源碼,果真是有一個DefaultControllerFactory類,而且不出意外的,它擁有一個CreateController方法。框架

public virtual object CreateController(ControllerContext context)
{
    ...

    var controller = _controllerActivator.Create(context);
    foreach (var propertyActivator in _propertyActivators)
    {
        propertyActivator.Activate(context, controller);
    }

    return controller;
}

但細推其使用的場合,只出如今ControllerFactoryProvider的構造方法內部,且僅是用於判斷所傳入的controllerFactory類型是不是DefaultControllerFactory。async

public ControllerFactoryProvider(
    IControllerActivatorProvider activatorProvider,
    IControllerFactory controllerFactory,
    IEnumerable<IControllerPropertyActivator> propertyActivators)
{
    ...

    _activatorProvider = activatorProvider;

    // Compat: Delegate to the IControllerFactory if it's not the default implementation.
    if (controllerFactory.GetType() != typeof(DefaultControllerFactory))
    {
        _factoryCreateController = controllerFactory.CreateController;
        _factoryReleaseController = controllerFactory.ReleaseController;
    }

    _propertyActivators = propertyActivators.ToArray();
}

再看ControllerFactoryProvider內部的CreateControllerFactory方法。這更像是一個真正建立Controller的工廠方法。ide

public Func<ControllerContext, object> CreateControllerFactory(ControllerActionDescriptor descriptor)
{
    ...

    if (_factoryCreateController != null)
    {
        return _factoryCreateController;
    }

    var controllerActivator = _activatorProvider.CreateActivator(descriptor);
    var propertyActivators = GetPropertiesToActivate(descriptor);
    object CreateController(ControllerContext controllerContext)
    {
        var controller = controllerActivator(controllerContext);
        for (var i = 0; i < propertyActivators.Length; i++)
        {
            var propertyActivator = propertyActivators[i];
            propertyActivator(controllerContext, controller);
        }

        return controller;
    }

    return CreateController;
}

建立方式分爲兩種,一種是使用自定義的工廠方法,另外一種是經過ControllerActivatorProvider的CreateActivator方法。code

public Func<ControllerContext, object> CreateActivator(ControllerActionDescriptor descriptor)
{
    ...

    var controllerType = descriptor.ControllerTypeInfo?.AsType();
    ...

    if (_controllerActivatorCreate != null)
    {
        return _controllerActivatorCreate;
    }

    var typeActivator = ActivatorUtilities.CreateFactory(controllerType, Type.EmptyTypes);
    return controllerContext => typeActivator(controllerContext.HttpContext.RequestServices, arguments: null);
}

明白瞭如何建立Controller,下面開始調查建立Controller的時機。orm

ControllerFactoryProvider類的CreateControllerFactory方法是被ControllerActionInvokerCache類的GetCachedResult方法調用。htm

public (ControllerActionInvokerCacheEntry cacheEntry, IFilterMetadata[] filters) GetCachedResult(ControllerContext controllerContext)
{
    var cache = CurrentCache;
    var actionDescriptor = controllerContext.ActionDescriptor;

    IFilterMetadata[] filters;
    if (!cache.Entries.TryGetValue(actionDescriptor, out var cacheEntry))
    {
        var filterFactoryResult = FilterFactory.GetAllFilters(_filterProviders, controllerContext);
        filters = filterFactoryResult.Filters;

        var parameterDefaultValues = ParameterDefaultValues
            .GetParameterDefaultValues(actionDescriptor.MethodInfo);

        var objectMethodExecutor = ObjectMethodExecutor.Create(
            actionDescriptor.MethodInfo,
            actionDescriptor.ControllerTypeInfo,
            parameterDefaultValues);

        var controllerFactory = _controllerFactoryProvider.CreateControllerFactory(actionDescriptor);
        var controllerReleaser = _controllerFactoryProvider.CreateControllerReleaser(actionDescriptor);
        var propertyBinderFactory = ControllerBinderDelegateProvider.CreateBinderDelegate(
            _parameterBinder,
            _modelBinderFactory,
            _modelMetadataProvider,
            actionDescriptor);

        var actionMethodExecutor = ActionMethodExecutor.GetExecutor(objectMethodExecutor);

        cacheEntry = new ControllerActionInvokerCacheEntry(
            filterFactoryResult.CacheableFilters, 
            controllerFactory, 
            controllerReleaser,
            propertyBinderFactory,
            objectMethodExecutor,
            actionMethodExecutor);
        cacheEntry = cache.Entries.GetOrAdd(actionDescriptor, cacheEntry);
    }
    else
    {
        // Filter instances from statically defined filter descriptors + from filter providers
        filters = FilterFactory.CreateUncachedFilters(_filterProviders, controllerContext, cacheEntry.CachedFilters);
    }

    return (cacheEntry, filters);
}

其值做爲ControllerActionInvokerCacheEntry對象的一部分被方法返回。對象

GetCachedResult方法的上層調用者是ControllerActionInvokerProvider類的OnProvidersExecuting方法。blog

public void OnProvidersExecuting(ActionInvokerProviderContext context)
{
    ...

    if (context.ActionContext.ActionDescriptor is ControllerActionDescriptor)
    {
        var controllerContext = new ControllerContext(context.ActionContext);
        // PERF: These are rarely going to be changed, so let's go copy-on-write.
        controllerContext.ValueProviderFactories = new CopyOnWriteList<IValueProviderFactory>(_valueProviderFactories);
        controllerContext.ModelState.MaxAllowedErrors = _maxModelValidationErrors;

        var cacheResult = _controllerActionInvokerCache.GetCachedResult(controllerContext);

        var invoker = new ControllerActionInvoker(
            _logger,
            _diagnosticSource,
            controllerContext,
            cacheResult.cacheEntry,
            cacheResult.filters);

        context.Result = invoker;
    }
}

ControllerActionInvokerCacheEntry對象又被做爲ControllerActionInvoker對象的一部分爲ActionInvokerProviderContext的Result屬性賦值。ip

再往上跟蹤,到了ActionInvokerFactory類的CreateInvoker方法。

public IActionInvoker CreateInvoker(ActionContext actionContext)
{
    var context = new ActionInvokerProviderContext(actionContext);

    foreach (var provider in _actionInvokerProviders)
    {
        provider.OnProvidersExecuting(context);
    }

    for (var i = _actionInvokerProviders.Length - 1; i >= 0; i--)
    {
        _actionInvokerProviders[i].OnProvidersExecuted(context);
    }

    return context.Result;
}

而它的調用者即是MvcRouteHandler或者MvcAttributeRouteHandler。

public Task RouteAsync(RouteContext context)
{
    ...

    context.Handler = (c) =>
    {
        var routeData = c.GetRouteData();

        var actionContext = new ActionContext(context.HttpContext, routeData, actionDescriptor);
        if (_actionContextAccessor != null)
        {
            _actionContextAccessor.ActionContext = actionContext;
        }

        var invoker = _actionInvokerFactory.CreateInvoker(actionContext);
        if (invoker == null)
        {
            throw new InvalidOperationException(
                Resources.FormatActionInvokerFactory_CouldNotCreateInvoker(
                    actionDescriptor.DisplayName));
        }

        return invoker.InvokeAsync();
    };

    ...
}

到了這裏建立Controller的工廠方法尚未被實際調用,此時Controller仍是不存在的。因此還須要完成執行ControllerActionInvoker的InvokeAsync方法,或者更準確地說是其基類ResourceInvoker的InvokeAsync方法。

public virtual async Task InvokeAsync()
{
    try
    {
        ...

        using (_logger.ActionScope(_actionContext.ActionDescriptor))
        {
            ...

            try
            {
                await InvokeFilterPipelineAsync();
            }
            ...
        }
    }
    ...
}

從InvokeFilterPipelineAsync方法開始,一系列的處理流程將依據不一樣狀態逐步展開。

private async Task InvokeFilterPipelineAsync()
{
    var next = State.InvokeBegin;

    var scope = Scope.Invoker;

    var state = (object)null;

    var isCompleted = false;

    while (!isCompleted)
    {
        await Next(ref next, ref scope, ref state, ref isCompleted);
    }
}

而到了State.ActionBegin這一步(ControllerActionInvoker類的Next方法),終於能找到Controller工廠方法被執行的場合。

private Task Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
{
    switch (next)
    {
        case State.ActionBegin:
            {
                var controllerContext = _controllerContext;

                _cursor.Reset();

                _instance = _cacheEntry.ControllerFactory(controllerContext);

                _arguments = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

                var task = BindArgumentsAsync();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ActionNext;
                    return task;
                }

                goto case State.ActionNext;
            }
        ...
        }            
    }
}

最後以一張流程圖總結上面的探尋過程。

相關文章
相關標籤/搜索