Communication between MVC Controllers

1

I'm having trouble communicating between Controllers each in a different Area , the public methods of the second controller are not available in the first one. Is there any way to do this? Here's the example below:

public class AController : Controller
{
    ...
    public ActionResult GerarBoleto(){
        ...
        PessoaFinanceiro pessoaFinanceiro = BController.ObtemPessoaFinanceiro(pessoa, dataAtual);
        ...
    }
    ...

}

.

public class BController : Controller
{
    ...
    public PessoaFinanceiro ObtemPessoaFinanceiro(Pessoa pessoa, DateTime dataAtual){
        ...
        return pessoaFinanceiro;
    }
    ...

}
    
asked by anonymous 21.10.2017 / 06:46

1 answer

2

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.

    
21.10.2017 / 10:37