Below is the source code of ControllerActivatorProvider
https://source.dot.net/#Microsoft.AspNetCore.Mvc.Core/Controllers/ControllerActivatorProvider.cs,64
public Func<ControllerContext, object> CreateActivator(ControllerActionDescriptor descriptor)
{
var controllerType = descriptor.ControllerTypeInfo?.AsType();
// ...
var typeActivator = ActivatorUtilities.CreateFactory(controllerType, Type.EmptyTypes);
return controllerContext => typeActivator(controllerContext.HttpContext.RequestServices, arguments: null);
}
I don't understand why typeActivator
is created by ActivatorUtilities.CreateFactory(controllerType, Type.EmptyTypes)
where Type.EmptyTypes
is Array.Empty<Type>()
, but when we create controller, we almost will define a contructor that takes parameters which will be resolved by DI, e.g HomeController
:
public class HomeController: Controller
{
IUserRepository userRepo;
public HomeController(IUserRepository userRepo)
{
userRepo = this.userRepo;
}
}
so why the source code uses Type.EmptyTypes
, and how can it work if the controller type receives no arguments?
CodePudding user response:
Notice that the first argument is the service provider:
typeActivator(controllerContext.HttpContext.RequestServices, arguments: null);
And note what it says in the docs
A factory that will instantiate instanceType using an System.IServiceProvider and an argument array containing objects matching the types defined in argumentTypes
So the second one is only used for directly provided types. All the rest are gotten from the service provider. In this case none are provided directly.