IControllerFactory vs IControllerActivator asp.net core

In order to create a controller instance, ASP.NET Core obtains an instance of IControllerFactory and uses it for controller creation.

However, if you look at the ASP.NET Core DefaultControllerFactory implementation, you will see that both the IControllerFactory and IControllerActivator are actually used for controller creation, because DefaultControllerFactory uses IControllerActivator to create an instance of the controller.

DefaultControllerFactory requires a dependency of type IControllerActivator to be passed in the constructor:

public DefaultControllerFactory(
    IControllerActivator controllerActivator,
    IEnumerable<IControllerPropertyActivator> propertyActivators)
{
    if (controllerActivator == null)
    {
        throw new ArgumentNullException(nameof(controllerActivator));
    }

    if (propertyActivators == null)
    {
        throw new ArgumentNullException(nameof(propertyActivators));
    }

    _controllerActivator = controllerActivator;
    _propertyActivators = propertyActivators.ToArray();
}

and CreateController and ReleaseController methods basically just invoke the IControllerActivator's corresponding methods:

public object CreateController(ControllerContext context)
{
    ... some null checks

    // _controllerActivator is of type IControllerActivator
    var controller = _controllerActivator.Create(context);
    foreach (var propertyActivator in _propertyActivators)
    {
        propertyActivator.Activate(context, controller);
    }

    return controller;
}
public void ReleaseController(ControllerContext context, object controller)
{
    ... some null checks

    _controllerActivator.Release(context, controller);
}

The only additional thing that the default instance of IControllerFactory does is invoking property activators (instances of IControllerPropertyActivator).

What you can do in your case?

  • Option 1: Provide your own implementation of IControllerFactory and create controller instances however you want. In this case IControllerActivator will not be used unless you require it.
  • Option 2: Use the default implementation of IControllerFactory, but provide your own implementation of IControllerActivator which will be used by DefaultControllerFactory.