How do I create a concise and RESTful wizard under MVC? - ruby-on-rails

I try to be as RESTful as possible in building applications but one thing that I'm never sure about is how to create a wizard-type work flow, be RESTful and concise.
Take, for example, a multi-page sign-up process.
Option 1: I can create a controller for each step and call new or edit when user gets to that step (or back to it). I end with step1_controller, step2_controller, etc...
Option 2: I can create a one controller and track where they are in the sign-up process with a param, session variable, state-machine - whatever. So I'd have signup_controller/step?id=1
The first option is strictly REST, but not very concise and ends with some number of extra controllers. The second options is more concise, but breaks REST, which I'm willing to do, but I don't take it lightly.
Is there a better option?
I'm working in ruby on rails, but this question applies to other MVC implementations, like ASP.NET MVC

If you apply some DDD logic here, which compliments the "M" in MVC, the state of the UI (registration progress) belongs in the Application Layer, which can talk directly with the Domain and Infrastructure layers (Four layers: UI, Application, Domain, and Infrastructure). The concept of DDD makes you "think" about how to solve the solution in code first. Let's step through this...
It's the Progress Bar
The state you want to maintain here is the step or progress of the registration. So, my first step would be to document progress or "steps". Such as, Step 1: Get Username/Pass, Step 2: Get Email. In this case, I would apply logic to "move" the Model to the next step. Most likely with a NextStep() method on the a RegistrationService (RegistrationService.NextStep()).
Ah, but it belongs in the App layer
I would create a service in the Application layer called RegistrationService. I would place a method on here called NextStep(). But remember, the Domain would not hold the state of the model here. In this case, you'd want to focus the state at the Application layer. So in this case, NextStep() would act upon not a model object (since it is not part of the Domain responsibility), but instead the UI. So, you need something to retain the state of the Registration process.
Get away from the Domain Model, how about a ViewModel?
So now we know we have to retain the state of something in the UI. MVC allows for a concept called ViewModels (in ASP.NET MVC, not sure what RoR calls it). A ViewModel represents the model that will be displayed by the view, and/or partial views.
The ViewModel would be an excellent place to save the state of this object. Let's call it, RegistrationProgressViewModel() and stick a NextStep() method on it. This, of course, means that the Application layer would have to retain the location of the RegistrationProgressViewModel, and the APplication layer would change the internals of it based on NextStep actions. if it is complex, you may want to create a RegistrationProgressService() in the application layer and place the NextStep() within it to abstract your logic away.
How to pass the ViewModel around?
The final piece is how to track the state of that object. Since web applications are stateless, you have to retain control by some other means then the application. In this case, I would revert to either: 1) Serializing the ViewModel to the client and letting the client pass it back and forth, or 2) Keep a server-side copy of the ViewModel, and pass some type of identifier back and forth to the client and back.
This is a good example to think about, as I have not performed this myself yet. For #2, the most secure and insured way of saving the state of this ViewModel is to persist it to the via the Infrastructure layer (yes, the APp layer can talk directly to the Infrastructure layer). That seems a lot of work to me, for something that may die off and I would have partial registrations sitting in my DB.
But, #2 would keep the user's private info (username, password, email, CC #, etc) all on the server side and not pass it back and forth.
Finally, an answer!
So, after walking through it, we came up with:
Create a RegistrationProgressViewModel() in the Application layer.
Create a RegistrationProgressService(), with a NextStep(ViewModel vm) method, in the Application layer.
When NextStep() is executed, persist the ViewModel to the database through the Infrastructure layer.
This way, you never have to track what "step?id=2" on the View or UI itself, as the ViewModel gets updated and updated (Authenticated, Verified, persisted to DB) as you move forward.
So, your next concern would be to "move forward" in the UI. This is easily done with 1 controller, using step or named steps.
I apologize, but I am writing C# code below as that is my language.
public class RegistrationController : Controller
{
// http://domain.com/register
public ActionResult Index()
{
return View(new RegistrationProgressViewModel);
}
// http://domain.com/register
// And this posts back to itself. Note the setting
// of "CurrentStep" property on the model below.
//
public ActionResult Index(
RegistrationProgressViewModel model)
{
// The logic in NextStep() here checks the
// business rules around the ViewModel, verifies its
// authenticity, if valid it increases the
// ViewModel's "CurrentStep", and finally persists
// the viewmodel to the DB through the Infrastructure
// layer.
//
RegistrationProgressService.NextStep(model);
switch (model.CurrentStep)
{
case 2:
// wire up the View for Step2 here.
...
return View(model);
case 3:
// wire up the View for Step3 here.
...
return View(model);
case 4:
// wire up the View for Step4 here.
...
return View(model);
default:
// return to first page
...
return View(model);
}
}
}
You'll notice that this abstracts the "Business Logic" of verifying the model's internal state into the RegistrationProcessService.NextStep() method.
Good exercise. :)
In the end, your "RESTful" url is a nice and clean POST to: /register, which expects a ViewModel with specific properties filled out. If the ViewModel is not valid, /register does not advance to the next step.

I'm actually less concerned about maintaining REST in a one-shot wizard. REST is most important, I think, with repeatable actions -- you want the url to be basically bookmarkable so that you get back the same view of the data regardless of when you go there. In a multi-step wizard you have dependencies that are going to break this perspective of REST anyway. My feeling is to have a single controller with potentially separate actions or using query parameters to indicate what step you are on. This is how I've structured my activation wizards (which require multiple steps) anyway.

Although the answers are very nice options indeed I still use the approach given in:
Shoulders of Giants | A RESTful Wizard Using ASP.Net MVC.
It is definitely worth a look. Though I must say, the answers given here make me think to remake this wizard when I have the time.

Related

What's the recommended place to perform validation: ViewModel, Model or Controller?

I have a registration page and would like to perform some validation (in addition to the StringLength and Required annotations on my ViewModel) for duplicate usernames and email addresses. Currently I perform this validation in my controller when the registration form is posted back. I'm not sure if this is the right place to do it though.
I can't imagine the ViewModel to be the right place as it would require the ViewModel to have a reference to my UserRepository. Does it make sense to have this kind of validation in the model classes?
If so, how do I implement this on the model so I can check if the information is valid before I sent it into my repository?
Update
Code of my controller action:
if (ModelState.IsValid)
{
if (!_userRepository.Exists(registerViewModel.Username))
{
if (!_userRepository.EmailExists(registerViewModel.Email))
{
_userRepository.Add(
new User
{
Created = DateTime.Now,
Email = registerViewModel.Email,
Password = registerViewModel.Password,
Username = registerViewModel.Username
});
_userRepository.SaveChanges();
TempData["registrationDetails"] = registerViewModel;
return RedirectToAction("Confirm");
}
else
{
ModelState.AddModelError(string.Empty, "This email address is already in use.");
}
}
else
{
ModelState.AddModelError(string.Empty, "This username is already taken.");
}
}
return View(registerViewModel);
}
Update 2
Should the domain model care about such constraints as duplicate user names or email addresses or is this something that the controller layer should worry about?
Update 3
It seems that putting the validation logic in the controller makes the most sense as it can be reused in remote validation and in model validation on submit. Is something like checking for duplicates generally a thing that should be done in controllers or does it make sense to have these kind of checks in a domain model?
Thanks,
I would perform it both on the frontend (ajax perhaps) and backend - which depends on your solutions architecture.
I like to let users know immediately if there's going to be a registration issues.
In my typical setup of a data layer / business layer and presentation layer, I would perform the dup checks in the business logic and have the controller call that piece of code (in addition to an ajax lookup on the front end for users).
As a bit of a side note: I generally prefer to only use MVVM (with view models) in windows applications. Combining MVC with MVVM can make things unnecessarily complicated
I would suggest that you do this in Controllers.
The main reason is that whatever the structure of the app be, you would definitely need to use Ajax to notify the user whether the username has already been taken or not. Otherwise it's just bad usability which doesn't justify your code structure.
And for that you would like to have a action method which could ajax-ly see if the username exists or not.
Overall, it does mean you may end up with two sets of validation method (UI and model) but its all for a good cause.
Also to make a good usable site you would definitely be using a Javascript framework like knockoutjs or backbone. Thats true MVVM and in that case having your ViewModels being the Model layer classes (as Chris mentioned) is not a good idea. So basically you'll end up with two sets of validation anyways.
As Rob said in the comments, it does depend on the structure of your application. I tend to have a double validation (Validation on my ViewModels as well as validation on my service layer) to ensure that the data that hits the service is valid. This helps because my services get used by multiple clients, but the views and ViewModels are client specific. Front end validations have the advantage of instant feedback, and the backend validations help keep your data clean.
My suggestion is - For validation, such as duplicate email address and user name- to keep your validation methods in controller.
Or in your Validation Layer - which will be used in between view model and data layer
for MVC3 you will be able to add methods in controller as a actions using Remote attribute to your property in view model for instant results
You should validate in both the View (client-side) and Controller (server-side). If you have MVC 3, you can use the new RemoteAttribute. It uses jQuery to make a server-side call, in which you could check for the existence of a user or email address.

Is it okay to hit the database from a custom model binder?

Say I have an object that gets some data from HttpPost and some from the database. I think I want to allow the ModelBinder to go to the database/repository for the that data missing from the post. In practice, is this a good or bad idea?
I've decided to edit my original answer given my thinking on these types of things has evolved since early 2010.
In my original answer, I basically expressed that, while my instincts told me you shouldn't do this, I was uncomfortable saying we shouldn't without being able to articulate why.
Now, I'd recommend against this on the grounds that the responsibility of a Model Binder is to translate a user request into a Request Model and that retrieving data outside of what can be derived from the request goes beyond this scope of responsibility.
I would say a bad idea. The idea of the model binder is that it takes the parameters from the request and creates your model from those. If your model binder, behind the scenes, fills in some of the details from the database this breaks the paradigm. I'd much rather expose the database call in my controller by explicitly fetching the required extra data from the database directly. Note that this could be refactored into a method if used frequently.
I think this is perfectly fine and use this technique all the time.
The only arguments against are very pedantic and amount to arguing over philosophy. IMHO you can put "fill in missing posted data" code into you MVC app as a method in your base controller vs. method in you ActionFilter vs method in you ModelBinder. It all depends on who get what responsibility. To me the model binder can do a lot more than simply wire up some properties from posted values.
The reason I love doing database calls in my modelbinder is because it helps clean up your action methods.
//logic not in modelbinder
public ActionResult Edit( KittyCat cat )
{
DoSomeOrthagonalDatabaseCall( cat );
return View( new MODEL() );
}
vs.
//logic in model binder
public ActionResult Add( KittyCat cat )
{
return View( new MODEL() );
}
It violates the way MVC is supposed to work. ModelBinder is for binging Models from the data that comes from the view. Populating missing info from the database is something that is supposed to be handled by the controller. Ideally, it would have same data layer/repository class that it uses to do this.
The reason it should be in the controller is because this code is business logic. The business rules dictate that some data may be missing and thus it must be handled by the brains of the operation, the controller.
Take it a step further, say you want to log in the DB what info the user isn't posting, or catch an exception when getting the missing data and email admins about it. You have to put these in your model binder this way and it gets more and more ugly with the ModelBinder becoming more and more warped from its original purpose.
Basically you want everything but the controller to be as dumb and as specialized as possible, only knowing out how to carry out its specific area of expertise which is purely to assist the controller.
I would say, no.
Here's why: It would create a dependency on your database for testing your controller actions that would not be easy to abstract out.
I would say it is ok. The argument that creates dependency to database is a false argument for 2 reasons:
1- Database access should be abstracted via repository interfaces. Repository interfaces are part of the domain model and their implementation is part of the infrastructure/data access layer. So there is no dependency to the database.
2- Model Binders and Controllers are both part of presentation layer implemented using ASP.NET MVC Framework. If Controllers are allowed to access database using repository interfaces, how come Model Binders are not allowed?
Also, there are situations that you'd "better" fill the missing data in your model from Model Binders. Consider the scenario where you have a drop-down list on your view. The first time the view is loaded, the drop-down list is populated. The user submits the form but the validation fails. So you'll need to return the form again. At this stage, you'll have to re-populate the list in the Model for the drop-down list. Doing this in Controller looks ugly:
public ActionResult Save(DocumentViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Categories = _repository.GetAll();
return View(viewModel);
}
}
I believe the initialization of Categories here is ugly and like a code smell. What if you had a few properties that needed to be filled out from database? What if you had more than 1 action that had DocumentViewModel as an argument? You'd have to repeat this ugly step over and over. A better approach is to fill all the properties of the model using the Model Binder and pass it to the Controller. So the object that is passed to the controller is in a "consistent" state.

ASP.NET MVC: Best practices for keeping session state in a wizard-like app

Let's say I have a Web application implemented like a set of wizard pages to edit a complex object. Until the user clicks on the "Finish" button, the object doesn't get saved to the back-end system (a requirement), so in the meantime I have to keep the whole information about the object in some kind of a session state.
Also, some of the wizard pages have to show combo and list boxes with potentially large number of items. These items are fetched from the back-end system using a Web service.
Coincidentally, the wizard allows the user to freely jump from one wizard page to any other (using tab links on top of the form), so it's not a simple "next, next... finish" thing.
Additional constraint: the Web application runs on a Web farm and the customer is weary of using server-side session state. In the best case they want to keep the size of the session state minimal (they had problems with this in the past).
So basically there are two problems here:
How/where to keep data entered by the user in the Wizard?
Whether to cache the combo/list items received from the back-end and if so, where?
Options I'm considering:
Storing the object in a WebForms-like ViewState (by serializing it into the HTML page). This would also include the combo box items. Obviously, there could be a problem with HTML pages becoming very large and thus Web application will be slow.
Storing it into server-side session state, regardless of the customer's wishes and without knowing how the performance will be affected until it is tested on the actual Web farm (late in the project).
I cannot decide between the two. Or is there another alternative?
Why cache at all? You could just have the tabbed pages where each page is a div or panel and just display the current div relating to your tab. That way you dont have to keep track and process all the inputs when the user submits the form.
Is it possible to store the wizard data in a temporary table in the database? When the user finishes the wizard the data is copied from the temporary table and deleted. The temporary table includes a timestamp to remove any old uncompleted data.
As Daisy said, it doesn't have to be cached. You could also use hidden form fields. Because these could map to the same object on each controller action, you could progressively build the object through successive pages.
//Here's a class we're going to use
public class Person
{
public int Age {get;set;}
public string Name {get;set;}
public Person()
{
}
}
//Here's the controller
public Controller PersonCreator
{
public ActionResult CreatePerson()
{
//Posting from this page will go to SetPersonAge, as the name will be set in here.
return View();
}
public ActionResult SetPersonAge(Person person)
{
//This should now have the name and age of the person
return View(person);
}
}
//Here is your SetPersonAge, which contains the name in the model already:
<%= Html.Hidden("Name", Model.Name) %>
<%Html.TextBox("Age") %>
And that's pretty much it.
I can suggest a few more options
Having the entire wizard as a single page with the tabs showing and hiding content via javascript on the client-side. This may cause the the initial page to load slower though.
Caching the data at the server using the caching application block (or something similar). This will allow all the users to share a single instance of this data instead of duplicating across all sessions. Now that the data is lighter, you may be able to convince the customer to permit storing in the session.
There is a lot of resistance in the MVC community against using Sessions. Problems are that a lot of us developers are building login systems like a bank website. One could argue for hidden fields and that works for some situations but when we need to time a user out for security and compliance, then you have several options. Cookies are not reliable. Relying on Javascript timers are not reliable and are not 508 compliant as the goal should be to degrade gracefully. Thus for a Login, a Session is a good option. If you write the time to the client browser, to the server database or server file system, you still have to manage the time per user.
Thus use Sessions sparingly, but don't fear them. For the wizards, you technically can serialize hidden fields passing them around. I suspect the need and scope will become much greater and an authorization/authentication implementation with Sessions will be the crux of the application.
If you cannot use ajax (for validation & dropdowns and ability to convert wizard to tabbed page) and cannot use html5 (for dropdown caching and form state saving in local storage), then I think you are pretty out of available "best practices" and you have to resort to bad (or worse) one.
As MVC is opponent of WebForms regarding session usage, maybe you can use a workaround? For example, besides storing all these values in some temporary database records you need to clean up later, you could set up AppFabric extension for Windows Server and use it to store dropdown list items (and scope can be for all users, so if more users are using system at the same time you need only one call to web service to refresh cache), and also to temporary store your objects between steps. You can set your temporary objects in AppFabric to automatically expire so cleanup is not necessary. It can also be of help for speeding up other parts of your system if you extensively call another system over web services.
I've been dealing with the same issue and, while my requirements are a little simpler (keeping state for just a few strings), my solution may work for you. I'd also be interested in hearing others thoughts on this approach.
What I ended up doing is: in the controller I just dump the data I want into the Session property of the Controller and then pull it out next time I need it. Something like this for your situation:
//Here's the controller
public Controller PersonCreator
{
public ActionResult CreatePerson()
{
//get the age out of the session
int age = (int)(Session["age"]);
//do something with it...
return View();
}
public ActionResult SetPersonAge(Person person)
{
//put the age in the session
Session.Add("age", person.Age);
return View(person);
}
}
The thing I like about this is I don't have to put a bunch of hidden params around on my view pages.
The answer to this can be found in Steve Sanderson's ASP.NET MVC 2/3, and requires a reference to the MVC Futures assembly. This link to Google Books is exactly what he does.
In essence, you serialize the wizard data to the View. A hidden field is rendered storing all of the acquired information.
Your controller can work out what to do through the use of the OnActionExecuting and OnResultExecuted (to cater for redirects) to pass it to the next view.
Have a read - he explains it much more thoroughly than I can.

ASP.NET MVC: Authorization inside an Action - Suggested Patterns or this is a smell?

I have an ASP.NET MVC application using Authorization Attributes on Controllers and Actions. This has been working well but a new wrinkle has shown up.
Object: Shipment
Roles: Shipping, Accounting, General User
The Shipment moves through a workflow. In state A it can be edited by Shipping only. In state B it can be edited by Accounting only.
I have a ShipmentController, and an Edit Action. I can put an Authorization attribute to limit the Edit action to only those two roles, but this doesn't distinguish between which state the Shipment is in. I would need to do some Authorization inside the action before the service call to determine if the user is really authorized to execute the edit action.
So I'm left with two questions:
1) Whats a good way to have authorization inside an Action. The Controller Action calls to a service, and the service then makes appropriate calls to the Shipment object (update quantity, update date, etc). I know for sure I want the Shipment object to be agnostic of any authorization requirements. On the other hand, I don't have a real grasp if I would want the service object to know about authorization or not. Are there any good patterns for this?
2) Is my problem actually a symptom of bad design? Instead of ShipmentController should I have a StateAShipmentController and StateBShipmentController? I don't have any polymorphism built into the Shipment object (the state is just an enum), but maybe I should and maybe the Controllers should reflect that.
I guess I'm after more general solutions, not a specific one for my case. I just wanted to provide an example to illustrate the question.
Thanks!
I don't see a problem with an Action method doing further authorization checks within it. You can leverage the Roles provider for the fine-grained authorization you're looking for. Please excuse my syntax here - it's likely rough and I haven't tested this.
[Authorize(Roles="Shipping, Accounting")]
public ActionResult Edit(int id)
{
Shipment shipment = repos.GetShipment(id);
switch (shipment.State)
{
case ShipmentState.A:
if (Roles.IsUserInRole("Shipping"))
return View(shipment);
else
return View("NotAuthorized");
break;
case ShipmentState.B:
if (Roles.IsUserInRole("Accounting"))
return View(shipment);
else
return View("NotAuthorized");
break;
default:
return View("NotAuthorized");
}
}
Your authorization attribute could get the Shipment from action parameters or route data and then make a decision.
For number 1, there are a number of patterns that enable rich behavior in domain objects. In double-dispatch, you pass a reference to a service abstraction (interface) to a method on the object. Then it can do its thing. You can also write an application service that takes the Shipment and does the work.
On number 2, not necessarily. You may need to abstract the concept of a "contextual Shipment" into a service that figures out which Shipment context you're in. But I'd YAGNI that until you need it again.
You could take a look at Rhino.Security, it could be used to implement user authorization in these kinds of scenarios.
In addition to the answer above, you can return a HttpUnauthorizedResult instead of creating your own view for NotAuthorized. This will redirect to the login page and behave just like the usual [Authorize] attribute

ASP.NET MVC - User Input and Service/Repository - Where to do Validation?

This might be too opinionated a question, but looking for help!
I have been trying to refine my ASP.NET MVC program structure. I just started using it at preview 5 and it is my first foray into business application development -- so everyting is new!
At the controller level, I have a service object responsible for talking to the repository and taking care of all business logic. At the action level, I have an object that holds all view data -- user input and generated output -- that I'll call view object (is there a general term for this?). Unlike most examples I see, this object is not a database object, but an object specific to the view.
So now I want to add user validation. The problem is, I'm not sure where to put it. It makes the most sense to me to do it in the Service layer. The Service layer is responsible for all the business logic and validation is business logic. On the other hand, most validation frameworks that I see are for validating an object, which makes me think the view object should be validation aware. Finally, there are some validation methods that would require a database connection (checking if a user input field has a corresponding database record for example), and the view object has no concept of a database, only the Service.
So some options I see are:
Do validation in the Service.Method on the parameters passed to the method.
Do validation in the view object before calling Service.Method.
Do validation in the view object but make the Service.Method require a view object reference so it is initiating the validation on the object.
I'm sure there are more. I'm curious of how other people handle user input validation in the MVC sense. I've previously used the Enterprise Validation Block and liked being able to use stock validators for everything, but I'm not sure how to make it fit into a seperate view object and service layer. It would be easy if they (view object / service) were the same object, which is maybe what people do? Like I said, its all new to me and I'm looking for best practice / patterns.
I typically do basic validation (required fields, email format, etc.) in the controller action when the form is submitted. I then let the business layer handle validation that requires business knowledge. I usually double check the basic stuff in the business layer as well, so if I expose that logic through web services or use it in another application later, I still have validation where it is most important (IMO).
There are some interesting links on this
MVC & MS Validation Application Block
MVC & Data Annotation Validators
Form Validation video
Personally, i've added validation to my Service layer objects (first two links). This way, if any method in any controller decides to call my service method .. the logic is all checked and boxed in one location. DRY.
That said, i also have some UI validation (3rd link) .. to reduce the roundtrip time.
Lastly, the current MVC dll's have the ability to pass error messages back to the UI .. so the view can display them nicely. Check out :-
ViewData.ModelState.AddModelError(key, message)
hth!
Check the following blog posts
http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/
http://www.emadibrahim.com/2008/09/08/client-server-side-validation-in-aspnet-mvc/
Take a look at the S#arp Architecture project. Validation is handled on the model to ensure that no entity is persisted to the database in an invalid state. It does this by using NHibernate.Validator and attaching it to NHibernate's save and update events.
Personally, this approach makes the most sense to me since you don't have to duplicate your validation logic in multiple controllers.
I was afraid I'd get no replies for my post, happy to be wrong!
I've read those links before, but probably a month or more ago, and re-reading them with what I understand now has been very helpful. I really like Steve Sanderson's post with the sliding scale, but wish he would show an example of validating something at the right-end of the spectrum.
As an example in his blog he gives: " 'usernames must be unique' will probably be enforced in your database". So would this be something like:
public static void SavePerson(Person person)
{
// make sure it meets some format requirement
// in this case the object is responsible for validation and the service layer is the caller
person.EnsureValid();
// todo: action to verify username is unique by checking database
// in this case the service layer is responsible for calling and implementing validation
// todo: action to save to database
}
This makes sense, and would show my trouble grasping where to put validation as it is inside both the service layer (very unique name) and view-object (verify formats).
Another concern I have is the service layer starts to balloon with validation logic. Maybe split it out to a different class or something? In my case some validation logic might be shared between services, so I would like to think of a DRY way to implement this. Fun stuff to think about!
Emad Ibrahim's link is great in that once I start to understand this process a bit more I was going to look for a way to generate javascript client-side validation using the same set of rules without having to repeat code. He already has that :)
I have heard about S#arp but not sat down and seen how it works (I'm not sure if there is much in the way of demos on it, or if downloading the code is the demo!). I'm not sure if doing validation on the database model only would be sufficient. It seems to me there would be plenty of valid model states with regards to the database that business logic would say are invalid (such as date ranges / must be before / after / etc). Those are the cases that are wracking my brain :)
Also, a link I liked (googled it after I saw Emad reply to Steves post with BLL and no idea what it meant... duh):
http://en.wikipedia.org/wiki/Business_logic_layer
So I didn't know it, but I think this is the model I'm writing to: Business Process object that handles data interactions, and Business Entities that are logical models rather than database models. I think I need to start reading some more fundamental patterns and practices with this stuff to better understand the concepts (it seems like a lot of this is stuff Java people write vs. .NET people). It might be time to take a step back :)
I have come across this same issue in a recent project. First, to restate the problem, I am trying to follow the domain-centric approach of DDD. I have entities composed into aggregates that can validate themselves, and the repositories verify validity on save. The UI can also get validity information from an aggregate in order to display error feedback to the client. The general approach is to leverage as much as possible ASP.NET MVC's model binding, and validation/form UI helpers. This creates the simple UI flow: 1) bind, 2) validate, 3) if valid, save, else re-populate view.
However, it is not directly obvious how to do leverage ASP.NET MVC and this simple flow when DDD services are involved. Originally, I developed my services as such:
public class SomeProcessService
{
public Result Execute(int anAggregateID, int anotherAggregateID, string someData)
{
// validate input
// if invalid, return failures
// else
// modify aggregates
// using (transaction)
// {
// save aggregates
// commit
// }
// return success
}
}
The problem is that the validation and the save are inextricably linked in the method. To leverage the MVC model binding, we need something that serves as a model to bind to. I am refactoring to this:
public class SomeProcessService
{
public class Request : IValidateable
{
public int AggregateID {get;set;}
public int AnotherAggregateID {get;set;}
public string SomeData {get;set;}
public Result Validate()
{
// validation
}
}
public void Execute(Request request)
{
// validate input by calling request.Validate()
// if invalid, throw new ValidationException(request)
// else
// modify aggregates
// using (transaction)
// {
// save aggregates
// commit
// }
// return success
}
}
This repurposes the Parameter Object pattern to separate method input validation. I can bind to a SomeProcessService.Request object in my controller, as well as get validation information there. If all is well, from my controller I initiate the service call using the Request object as the parameter. This approach seems to happily marry DDD services with ASP.NET MVC validation requirements.

Resources