I have a Blazor application with a server and a client where the client has a generic service that is used for CRUD operations for all different types in my project. This generic service then calls a specific controller in the server that executes the logic.
The client has a generic service that is used for all the different classes for all CRUD operations which calls different controllers on the server:
public async Task<IEnumerable<Type>> GetListAsync(){ string url = apiUrl + $"/api/{typeof(Type).Name}"; string authToken = await GetAccessTokenAsync(); logger.LogInformation("Retrieving list..."); using HttpClient httpClient = GetHttpClient(); return await HttpClientHelper.GetAsync<IEnumerable<Type>>(httpClient, url, authToken);}...Then the server has a generic controller with all methods that are common to all different services:
public class GenericController<Type, Identity, Filter> : ControllerBase where Identity : IIdentity{ private readonly IGenericService<Type, Identity, Filter> _service; public GenericController(IGenericService<Type, Identity, Filter> service, ILogger logger) { _service = service; this.logger = logger; } [AllowAnonymous] [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public virtual async Task<ActionResult<IEnumerable<Type>>> GetList() { try { result = await _service.GetListAsync(); return Ok(result); } catch (Exception ex) { return BadRequest(ex.Message); } }}Then in order for the MVC to discover the routes I need to implement controllers for each of the types in this way:
[Authorize][Route("api/[controller]")][ApiController]public class ErrorCodeController : GenericController<ErrorCode, ErrorCodeIdentity, ErrorCodeFilter>{ #region Construction/destruction ... /// <summary> /// Constructor. /// </summary> public ErrorCodeController(IErrorCodeService service, ILogger<ErrorCodeController> logger) : base(service, logger) { } #endregion}Now I wonder if there is any way to not need to implement each of the controllers in this way as they are mostly empty except for some specific controllers that implement special functionality.
I have googled about dynamic controllers but I haven't found much information of how to do this.
It would be very beneficial for me to not need to create an almost empty class for each controller as I have many entities/classes and I need one controller for each of those.