1

I have been using the following pattern for my controller actions:

public ActionResult Create(CreateViewModel model) { if( !ModelState.IsValid ) { return View(model); } var project = new Project { Name = model.Name, // ... }; projectRepository.Add(project); return RedirectToAction("Index"); } 

This works for simple scenarios, but I have had a few situations where a repository is not enough. I created a service layer / class that will handle saving the project and any extra business logic (not normal validations with fluent validation or data annotations).

public class ProjectService : IProjectService { void AddProject(Project project) { // do business logic // ... repository.Add(project); } } 

How can my service layer easily communicate with my controller?

These are the types of things I would like to communicate to the controller:

  • Business Logic / Validation errors
  • Database Failures (failed to save etc.)

How can I do this without just returning true/false or status codes from the service layer?

2 Answers 2

2

Be careful if you choose exceptions, these are expensive. It gives your controller code extra nesting too, depending on how many exceptions may be thrown. You should really only throw an exception for an exceptional condition, not something that should be handled by the normal flow of your application.

I would go with the other route Wouter de Kort suggested, use the return type of the service for a messaging object. You can key a return message object on a simple enum with the various cases the service may encounter. These look better in the controller because you can handle the enum with a switch/case rather than a try/catch.

Update

What a messaging object may look like:

public interface IServiceAbc { ServiceResponse InvokeMyService([params]); } public enum ResponseScenario { Success, DatabaseFailed, BusinessRuleViolated, ValidationRuleViolated } public class ServiceResponse { public ResponseScenario Scenario { get; internal set; } public string Message { get; internal set; } } 
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to return detailed messages when an error occurs you could always use Exceptions. Maybe define your own with specific details or reuse the ones that are already in the .NET Framework.

If that´s not an option you could always return a wrapper class which could contain more detailed error information and handle that in the Controller.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.