AutoActions for Skinny controllers–idea

How you generate actions in controllers ? Usually, you create a Business Logic class and then you expose via a controller in a WebAPI . And, if you are very careful, then you use the Skinny controllers concept  ( read more about it at 3 ways to keep your asp.net mvc controllers thin (jonhilton.net) ).

So this implies usually repeating code in order to call the functions / methods from the business logic class.  I can give an example:

public class RepositoryWF
     {
         private static readonly string[] Summaries = new[]
{
             “Freezing”, “Bracing”, “Chilly”, “Cool”, “Mild”, “Warm”, “Balmy”, “Hot”, “Sweltering”, “Scorching”
         };
         public WeatherForecast[] DataToDo(int i)
         {
             var rng = new Random();
             return Enumerable.Range(1, i).Select(index => new WeatherForecast
             {
                 Date = DateTime.Now.AddDays(index),
                 TemperatureC = rng.Next(-20, 55),
                 Summary = Summaries[rng.Next(Summaries.Length)]
             })
             .ToArray();

        }
     // more methods / actions

and the controller

[ApiController]
     [Route(“[controller]/[action]”)]
     public partial class WeatherForecastController : ControllerBase
     {

        private readonly ILogger<WeatherForecastController> _logger;

       
         private readonly RepositoryWF repository;
        
         public WeatherForecastController(ILogger<WeatherForecastController> logger, RepositoryWF repository)
         {
             _logger = logger;
             this.repository = repository;
            
         }

        [HttpGet()]
         public WeatherForecast[] DataToDo(int i)
         {
             return repository.DataToDo(i);
         }

    }

What if , instead of the writing code , we will auto – generate the actions ?

For this I was thinking that was fun to use Source Generators – https://devblogs.microsoft.com/dotnet/new-c-source-generator-samples/

The code should read like this:

[ApiController]
     [Route(“[controller]/[action]”)]
     public partial class WeatherForecastController : ControllerBase
     {

        private readonly ILogger<WeatherForecastController> _logger;

        [AutoActions]
         private readonly RepositoryWF repository;
        
         public WeatherForecastController(ILogger<WeatherForecastController> logger, RepositoryWF repository)
         {
             _logger = logger;
             this.repository = repository;
            
         }

    

    }

So the only thing that you should do is annotate your class with

        [AutoActions]
         private readonly RepositoryWF repository;

and the actions will be generated for you!