using Microsoft.AspNetCore.Mvc.ApplicationModels;
namespace DigitalData.Core.API
{
///
/// Provides a convention to remove controllers from the application based on specified conditions.
///
public class RemoveIfControllerConvention : IApplicationModelConvention
{
///
/// A list of conditions that determine if a controller should be removed.
///
private readonly List> _andIfConditions = new();
///
/// Applies the convention to the application, removing controllers that meet all specified conditions.
///
/// The application model representing the MVC application.
public void Apply(ApplicationModel application)
{
List controllersToRemove = new();
// Iterate over all controllers in the application.
foreach (var controller in application.Controllers)
{
// If all conditions are met for this controller, mark it for removal.
if (_andIfConditions.All(condition => condition(controller)))
controllersToRemove.Add(controller);
}
// Remove the controllers that met all conditions.
foreach (var controllerToRemove in controllersToRemove)
application.Controllers.Remove(controllerToRemove);
}
///
/// Adds a new condition to the list of conditions that a controller must meet to be removed.
///
/// The condition that determines if a controller should be removed.
/// The current instance of to allow for method chaining.
public RemoveIfControllerConvention AndIf(Func condition)
{
_andIfConditions.Add(condition);
return this;
}
}
}