Communication between MVC Controllers

Asked

Viewed 497 times

1

I’m having trouble making a communication between Controllers each in a Area different, the public methods of the second controller are not available in the first. Is there any way to do this? Follow 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;
    }
    ...

}

1 answer

2


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!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.