简体   繁体   中英

Single controller handles single API call for multiple models

I have multiple models for state,country,city,roles,emails etc.( 30 models) I have single controller which handles multiple api calls with single API method. I created 30 different Interfaces which implements to return List of objects.

public interface state
{
IEnumerable<state> GetState();
}
public interface city
{
IEnumerable<city> GetCity();
}

From the controller, through constructor injection, I'm injecting dependency and calling each method based on api parameter "section" using switch.

[Microsoft.AspNetCore.Mvc.HttpGet("{section}")]
        public ActionResult GetModelBySection(string section)
        {
            switch(section)
            {
                case "country":
                    return Ok(countryDAL.GetCountry());
                    ...
                    
                    ...

                default:
                    return Ok("Not Found");

            }
           
        }

Instead of injecting all 30 interfaces here, I tried using IGeneric. when I use IGeneric, I need to create multiple controller. I dont want to create multiple controller. Please help me here

Created IGeneric interface and implemented in each DAL, and made Controller generic.

public interface IGenericDAL<T> where T : class
    {
        Task<IEnumerable<T>> GetAllAsync();
        Task<T> GetByNameAsync(string name);
        long Add(T item);
        long Update(T item);
        long Delete(long id);

    }

 public class CityDAL : IGenericDAL<City> 
    {
          .......
    }

[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
    [ApiController]
    public class CommonController<T> : Controller where T : class
    {
        private IGenericDAL<T> _generic;

}

I tried as below:

public class GenericDAL<T> : IGenericDAL<T> where T : class
    {
        ......
    }

Regist in startup:

public void ConfigureServices(IServiceCollection services)
        {
            .....
            services.AddTransient(typeof(IGenericDAL<>), typeof(GenericDAL<>));
            ....
        }

In controller:

public class HomeController : Controller
    {
        
        private readonly IServiceProvider _serviceProvider;


        public HomeController( IServiceProvider serviceProvider)
        {
           
            _serviceProvider = serviceProvider;
        }

        public IActionResult SomeController()
        {

            var someservice = (GenericDAL<City>)_serviceProvider.GetService(typeof(IGenericDAL<City>));
             var cities = someservice.GetAllAsync().Result;
            return OK();
        }
}

The Codes excuted successfully:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM