1

I work with ASP.NET Core and have written an API controller as follows:

public class AcademicController : GenericController<Academic>
{
    public AcademicController(IRepository<Academic> repository) : base(repository) { }
}

This API functions perfectly. However, I would like to create a similar controller for every model. How can I achieve this?

public class [ModelName]Controller : GenericController<[ModelName]>
{
    public [ModelName]Controller(IRepository<[ModelName]> repository) : base(repository) { }
}

2 Answers 2

0

My first thought is to have one controller that would handle the needs of all models, current and future, but having all of the models you want to support this by implementing an interface. This would not create new classes, but handle everything from a routing point of view.

public class ModelController : GenericController<IModelInterface>
{
    public ModelController(IRepository<IModelInterface> repository) : base(repository) { }

And then you can implement some dynamic routing based on the model name.

However, if you definitely want a specific controller class for each, and more than just a routing solution, you could try source generators to create files for you at compile time. I admit I have not tried this with controllers, but it seems some others have. Disclaimer, I have not tried any of these things, but at minimum can help you if you are going the generator route.

Good luck and let us know how it goes or if I can help more on one of these paths!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. However, I think a method based on T4 might be a better approach.
0

I found a method, but it is not complete. I wrote a T4 file as follows:

<#
    // Define your model types
    var models = new string[] { "Academic", "Ostad", "Course" };
#>
using Core.Interfaces;
using DataAccessLibrary.Models;
using Microsoft.AspNetCore.Mvc;

namespace Snapp.site.Controllers
{
<#
    foreach (var model in models)
    {
#>
    public class <#= model #>Controller : GenericController<<#= model #>>
    {
        public <#= model #>Controller(IRepository<<#= model #>> repository) : base(repository) { }
    }
<#
    } // Closing foreach loop
#>
}

But I can't dynamically generate the models array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.