9
I am working on a prototype of an ASP.NET MVC application, where I want to leave my controller lean (with the least amount of code possible), for such, not making business logic in it, but rather in the business layer.
I have the business layer, where I have my class Usuario
, and in this layer I have interfaces that should be implemented by other layers. I will be using dependency injection.
My question is how to notify my controller on what worked or not, to notify or redirect the user, for example, when my controller calls Usuario.Cadastrar()
, there may be an error in filling in the data, the password may not meet the security requirements, the email may already be registered or there may be error in sending the confirmation email.
What the Register method should return to Controller? An enumerator like (ErroEnviarEmail
, SenhaFraca
, EmailCadastrado
), one Exception
for every possible path? A string etc..
public class Usuario
{
public Usuario()
{
}
public Usuario(IUsuarioRepositorio repositorio, ISeguranca seguranca, IEnviaEmail email)
{
this.repositorio = repositorio;
this.seguranca = seguranca;
this.email = email;
}
private IUsuarioRepositorio repositorio;
private ISeguranca seguranca;
private IEnviaEmail email;
public int Codigo { get; set; }
public string Email { get; set; }
public string Senha { get; set; }
public bool Cadastrar()
{
if (this.ValidarPreenchimento())
{
if (this.seguranca.ValidarSegurancaSenha(this.Senha))
{
if (!this.repositorio.EmailCadastrado(this.Email))
{
this.Senha = seguranca.Criptografar(this.Senha);
this.repositorio.Inserir(this);
this.email.EnviarEmailCadastro(this);
return true;
}
}
}
return false;
}
private bool ValidarPreenchimento()
{
if (string.IsNullOrEmpty(this.Email))
return false;
if (string.IsNullOrEmpty(this.Senha))
return false;
return true;
}
}
Why you have a "business layer"?
– Leonel Sanches da Silva
Several reasons. You can call this layer a domain, a service, or even a model, because it’s still a model. It’s about separation of responsibilities, and reuse. Today is ASP.NET MVC, but soon I can create a Web API, taking advantage of a lot, having to rewrite only the controllers of the API
– user26552
This will not be necessary in ASP.NET 5, not least because the Controller MVC6 for Web API and MVC should be the same. Your separation is only pertinent until the MVC5. Still I would like one more answer?
– Leonel Sanches da Silva
Interesting. I think that’s it for now. Before my controller had a little more code, and this concept anti "fat controller" left me a little confused on the question of the answers he needs. But the material passed by @bigown gave a direction.But I’m still studying.
– user26552