You may create a set of repositories for working with your entities, like CustomerRepository
, ProductRepository
from base interface like
public interface IBaseRepository
{
T Get<T>(int id);
void Save<T>(T entity);
}
and then extend your base controller class with repository type and its instance with any of DI frameworks
public abstract class GenericController<T, TRepo>
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<T>(id);
return View(model);
}
}
Example for CustomerController
public class CustomerController : GenericController<Customer, CustomerRepository>
{
}
where CustomerRepository:
public class CustomerRepository : IBaseRepository
{
public T Get <T>(int id)
{
// load data from DB
return new Customer();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…