I have a question and would like to better understand how class instantiation works. More specifically the most appropriate way of doing (if any) and the impacts of doing the wrong thing.
Assuming these two scenarios, which one should I use and Why?
Scenario 1: Instantiating out of methods.
public class PerfilController : Controller
{
PerfilDTO viewDTO = new PerfilDTO();
Perfil perfilNEG= new Perfil();
Recurso recursoNEG = new Recurso();
public ActionResult Cadastro()
{
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
public ActionResult Listagem()
{
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
}
Scenario 2: Instantiating within methods
public class PerfilController : Controller
{
public ActionResult Cadastro()
{
PerfilDTO viewDTO = new PerfilDTO();
Perfil perfilNEG= new Perfil();
Recurso recursoNEG = new Recurso();
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
public ActionResult Listagem()
{
PerfilDTO viewDTO = new PerfilDTO();
Perfil perfilNEG= new Perfil();
Recurso recursoNEG = new Recurso();
viewDTO.ListaPerfis = perfilNEG.ObterPerfis();
viewDTO.ListaRecursos = recursoNEG.ObterRecursos();
return View(viewDTO);
}
}
NOTE: If there is a different and better way, you can also alert me.