How to use ASP.NET MVC Generic Controller to populate right model

后端 未结 3 876
醉话见心
醉话见心 2020-12-08 12:12

I asked a question about ASP.NET MVC Generic Controller and this answer shows a controller like this:

public abstract class GenericController<         


        
3条回答
  •  萌比男神i
    2020-12-08 12:52

    You may create a set of repositories for working with your entities, like CustomerRepository, ProductRepository from base interface like

    public interface IBaseRepository
    {
      T Get(int id);
      void Save(T entity);
    }
    

    and then extend your base controller class with repository type and its instance with any of DI frameworks

    public abstract class GenericController 
            where T : class
            where TRepo : IBaseRepository, new()
        {
            private IBaseRepository repository;
    
            public GenericController() 
            {
                repository = new TRepo();
            }
    
            public virtual ActionResult Details(int id)
            {
               var model =repository.Get(id);
               return View(model);
            }
        }
    

    Example for CustomerController

    public class CustomerController : GenericController
    {
    
    }
    

    where CustomerRepository:

    public class CustomerRepository : IBaseRepository
    {
      public T Get (int id) 
      {
        // load data from DB
        return new Customer();
      }
    }
    

提交回复
热议问题