How do I share code between controllers of different models?

How do I share code between controllers of different models?

In the action of the super controller, I want to find out which controller (route) was called, and use this route name to load the corresponding model and use this model to query the database to go to the view.

I can easily do this in Ruby on Rails, does MVC do such a thing?

+3
source share
4 answers

You can use Generics:

public abstract class GenericRepositoryController<TModel> : Controller
{
    private readonly IRepository<TModel> _repository;

    protected GenericRepositoryController(IRepository<TModel> repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var model = _repository.GetAll();
        return View(model);
    }
}

public class EmployeeController : GenericRepositoryController<Employee>
{
    public EmployeeController(IRepository<Employee> repository) : base(repository)
    {
    }
}

public class CustomerController : GenericRepositoryController<Customer>
{
    public CustomerController(IRepository<Customer> repository) : base(repository)
    {
    }
}
+1
source

, , , , . , , .

0

, ?

" " - .

0

, . , , . , .

, . , , , , . -, . - ( , IOC). , , .

, . , .

0

Source: https://habr.com/ru/post/1751291/


All Articles