Bbijoabraham

extract-aspnetcore-controller-services

ASP.NET Core service extraction

aspnetcorecsharpmvccontrollerservice-extraction
Public
0 executions

Run locally

npx codemod extract-aspnetcore-controller-services

extract-aspnetcore-controller-services

Extracts conservative business and data-access logic from ASP.NET Core controllers into injected service interfaces and implementations.

What It Changes

The codemod targets C# ASP.NET Core controller classes that either:

  • end with Controller
  • inherit from Controller or ControllerBase

For straightforward action methods, it:

  • rewrites constructor injection from DbContext and repository dependencies to I{Name}Service
  • creates Services/I{Name}Service.cs and Services/{Name}Service.cs when missing
  • moves safe query, mapping, and business logic into the service method
  • preserves controller HTTP concerns such as route attributes, authorization attributes, ActionResult<T> signatures, Ok(...), and NotFound()
  • adds AddScoped<I{Name}Service, {Name}Service>() to Program.cs when missing

The default naming uses the controller name with conservative singularization where it is obvious:

  • CustomersController -> ICustomerService / CustomerService
  • ambiguous names fall back to plural-safe names such as ICustomersService / CustomersService

What It Skips

The transform is intentionally conservative. It skips methods when it sees controller-only APIs or patterns that are hard to extract safely, including references to:

  • HttpContext
  • ModelState
  • User
  • Request
  • Response
  • Url

It also skips more complex shapes such as async methods, methods without a clear ActionResult<T> payload, and controllers that already have conflicting service files.

Parameters

  • servicesDirectory: output directory for generated services. Default: Services
  • controllerInclude: comma-separated controller include globs checked inside the codemod. Default: **/*Controller.cs
  • controllerExclude: comma-separated controller exclude globs checked inside the codemod. Default: empty
  • runAiCleanup: whether to run the optional AI cleanup step after the AST transform. Default: true

Workflow

The default workflow runs in two stages:

  1. A deterministic AST/JSSG step rewrites eligible controllers, generates service files, and updates Program.cs.
  2. An optional AI step named AI review and cleanup reviews the resulting diff, fixes minor namespace/signature issues, and resolves conservative edge cases without unrelated rewrites.

Disable the AI follow-up with:

bash

Override the services directory or controller filters with:

bash

Example

Before:

csharp

After:

csharp

Development

bash

License

MIT

Ready to contribute?

Build your own codemod and share it with the community.