Skip to main content

Pattern: Service Layer (Separation of Concerns)

Description

The Service Layer pattern defines a boundary between the Application's Interface (MVC Controllers, API Endpoints) and the Domain Logic / Data Access.

The Controller's job is Orchestration (Receive input, Call Service, Return View). The Service's job is Business Logic (Validation, Calculation, Database transactions).

Context in WepNG

  • Current State: In many modules (e.g., MyWep, CRM), this separation is blurred ("Fat Controllers" doing DB access, or "God Services" doing too much).
  • Violation: MyWepApiManager (a Service) creating ViewModels (Presentation concern) is a typical violation seen in the MyWep module (Twin God Services).

The Standard Contract

  1. Controller: Depends on IService.
    • public class OrderController : Controller { private readonly IOrderService _service; }
  2. Service: Depends on IDbContext or IRepository.
    • public class OrderService : IOrderService { ... }

Benefits

  1. Testability: You can unit test the Service without instantiating a Web Server.
  2. Reusability: The same OrderService can be called by an MVC Controller, a WebAPI, or a Background Job.
  3. Clarity: "Twin God Services" (two services doing half the job each, confusingly) are avoided by having clear boundaries.

Rules for WepNG Refactoring

  • No HttpContext in Services: Services should not know about Request, Session, or ViewBag.
  • No HTML in Services: Services return Data (DTOs/Entities), not HTML strings.