I have faced some kind of confusion with IControllerFactory and IControllerActivator. I was trying to create controllers manually because it is required by my project. So, I looked at the Microsoft documentation. However, descriptions for both interfaces are confusing.
Descriptions for each interface
IControllerFactory:
Provides methods for the creation and disposal of controllers.
IControllerActivator:
Provides methods to create a controller.
Both are saying that they provide methods to create controllers. So, if I want to create a controller manually, which interface should I use? Is there any difference between them?
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?
IControllerFactory and create controller instances however you want. In this case IControllerActivator will not be used unless you require it.IControllerFactory, but provide your own implementation of IControllerActivator which will be used by DefaultControllerFactory.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With