MVC Validation - Keep it DRY with a service layer - What is best practice?

前端 未结 6 1020
栀梦
栀梦 2020-12-29 08:23

I am trying to adhere to best multi-layer design practices, and don\'t want my MVC controller to interact with my DAL (or any IRepository for that matter). It must go throug

6条回答
  •  温柔的废话
    2020-12-29 09:09

    I recommend you take advantage of the built in MVC validation by decorating your Model classes with data annotations. This is only for basic input validation which is different from processing business rules and validation. Data Annotations are great because they are useful for any consumer that is aware but don't adversely impact consumers that don't understand how to use them.

    I think you are right to use a service layer to abstract business rules and data access. You may want to do a couple of things to enhance the interaction between controller and service:

    1. Return XXXResult objects instead of void or primatives. If your service method is AddProduct then return AddProductResult or more broadly ProductServiceOperationResult. This result contains success/fail indicator as well as additional information.

    2. If you are using WCF then use Fault Contracts and exceptions.

    A typical MVC Application solution of mine looks like this:

    • MVC Website Project
    • xxx.Model (project, referenced by most layers)
    • xxx.Services (project)
    • xxx.DataAccess (project, sometimes merge with services)
    • others as needed

    Good luck!

提交回复
热议问题