I've been trying to set up an n-layered application in ASP.NET MVC 5. I've "converted" my account controller to look like this.
I would like some feedback as to whether this is in the right direction. What I'm trying to achieve is to off-load my Controllers and leave the logic to the Service. So basically, my Controller should just be doing the routing.
// all services inherit this to expose the DbContext
public class BaseService
{
protected AppDbContext db = new AppDbContext();
}
interface IAccountService
{
bool Login(HttpContextBase httpContext, string userName, string password);
bool Logout(HttpContextBase httpContext, HttpSessionStateBase session);
}
public class AccountService : BaseService, IAccountService
{
private UserManager<IdentityUser> userManager;
public AccountService()
{
userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
}
public bool Login(HttpContextBase httpContext, string userName, string password)
{
var user = userManager.Find(userName, password);
if (user != null) {
IAuthenticationManager authenticationManager = httpContext.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
authenticationManager.SignIn(userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie));
return true;
}
return false;
}
public void Logout(HttpContextBase httpContext, HttpSessionStateBase session)
{
IAuthenticationManager authenticationManager = httpContext.GetOwinContext().Authentication;
authenticationManager.SignOut();
session.Clear();
}
}
public class AccountController : Controller
{
private readonly IAccountService service;
public AccountController()
{
service = new AccountService();
}
public ActionResult Index()
{
return View();
}
public ActionResult Index(IndexViewModel viewModel)
{
ActionResult result;
if (service.Login(HttpContext, viewModel.UserName, viewModel.Password)) {
result = RedirectToAction("Index", "Home");
} else {
result = View(viewModel);
}
return result;
}
public ActionResult Logout()
{
service.Logout(HttpContext, Session);
return RedirectToAction("Index");
}
}