Although it is possible to make a controller
consume another controller
, this is a very bad approach.
The responsibility of controllers
is to control the data flow in the pipeline of the request. That is, what your application should do if it receives a request on a given route.
To solve your problem, the part of the code that needs to be shared is exactly what is inside action
of controller
.
Using your example to give my example. You must have a component that will deal with information about the "Financial Person". Ex:
public class PessoaFinanceiroRepositorio
{
PessoaFinanceiro ObtemPessoaFinanceiro(Pessoa pessoa, DateTime data)
{
// consulta no banco de dados
return pessoaFinanceiro;
}
}
Now, both controllers
will consume from the same repository.
public class AController : Controller
{
private readonly PessoaFinanceiroReposiroio _pessoaFinanceiroReposiroio;
public AController()
{
_pessoaFinanceiroRepositorio = new PessoaFinanceiroRepositorio();
}
public ActionResult GerarBoleto()
{
// ...
var pessoa = _pessoaFinanceiroRepositorio.ObtemPessoaFinanceiro(pessoa, data);
// ...
}
}
And in the second controller
.
public class BController : Controller
{
private readonly PessoaFinanceiroRepositorio _pessoaFinanceiroRepositorio;
public AController()
{
_pessoaFinanceiroRepositorio = new PessoaFinanceiroRepositorio();
}
public ActionResult QualquerOutraAction()
{
// ...
var pessoa = _pessoaFinanceiroRepositorio.ObtemPessoaFinanceiro(pessoa, data);
// ...
}
}
So you properly reuse the ObtemPessoaFinanceiro
method between controllers without mixing responsibilities.
PS: Controllers
must have Actions
as public methods. Other methods must be private
. If you need to share some code, isolate it in a separate component.