Although it is possible to make one controller
consume another controller
, this is a very bad approach.
The responsibility of controllers
is of control the data flow in the pipeline request. That is, what your application should do if you receive a request on a given route.
To solve your problem, the part of the code that must be shared is exactly what is inside the action
of controller
.
Using your example to give my example. You must have a component that will handle information relating to the "Financial Person". Ex:
public class PessoaFinanceiroRepositorio
{
PessoaFinanceiro ObtemPessoaFinanceiro(Pessoa pessoa, DateTime data)
{
// consulta no banco de dados
return pessoaFinanceiro;
}
}
Now, both of you 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 method ObtemPessoaFinanceiro
between controllers without mixing responsibilities.
PS: Controllers
must possess only Actions
as public methods. Other methods should be private
. If you need to share some code, isolate in a component the part.
I understand! I followed as you explained and it worked perfectly.. Obg!
– Eluander J. F. Lopes