0

Can you provide a code sample with basic architecture guidlines for creating service layer classes (which supposed to be consumed by web front-ends, web api etc.)?

Do you think this is a good tutorial? http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs

2
  • Doesn't matter that you are using MVC 4. It works the same with MVC 3 and MVC 2. The same goes for EF. Just use Google, there are hundreds of threads on this subject here at StackOverflow. Commented Jun 19, 2012 at 14:03
  • 3
    @Lean, yeah there are hundreds of shitty code samples on this subject :) for example, when people without any good reason implement custom repository and unit of work patterns over EF DbContext which already implements these two patterns. Commented Jun 19, 2012 at 20:01

1 Answer 1

4

I personally don't like how that article describes passing errors from a service layer back to the controller (with IValidationDictionary), I would make it work more like this instead:

[Authorize]
public class AccountController : Controller
{
    private readonly IMembershipService membershipService;

    // service initialization is handled by IoC container
    public AccountController(IMembershipService membershipService)
    {
        this.membershipService = membershipService;
    }

    // .. some other stuff ..

    [AllowAnonymous, HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (this.ModelSteate.IsValid)
        {
            var result = this.membershipService.CreateUser(
                model.UserName, model.Password, model.Email, isApproved: true
            );

            if (result.Success)
            {
                FormsAuthentication.SetAuthCookie(
                    model.UserName, createPersistentCookie: false
                );

                return this.RedirectToAction("Index", "Home");
            }

            result.Errors.CopyTo(this.ModelState);
        }

        return this.View();
    }
}

Or.. as mikalai mentioned, make the service throw validation exceptions, catch them in a global filter and insert into model state.

Sign up to request clarification or add additional context in comments.

1 Comment

Or, probably it could make less coding, if service throws exception on error which are handled using filter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.