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
ControllerorControllerBase
For straightforward action methods, it:
- rewrites constructor injection from
DbContextand repository dependencies toI{Name}Service - creates
Services/I{Name}Service.csandServices/{Name}Service.cswhen 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(...), andNotFound() - adds
AddScoped<I{Name}Service, {Name}Service>()toProgram.cswhen 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:
HttpContextModelStateUserRequestResponseUrl
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:ServicescontrollerInclude: comma-separated controller include globs checked inside the codemod. Default:**/*Controller.cscontrollerExclude: comma-separated controller exclude globs checked inside the codemod. Default: emptyrunAiCleanup: whether to run the optional AI cleanup step after the AST transform. Default:true
Workflow
The default workflow runs in two stages:
- A deterministic AST/JSSG step rewrites eligible controllers, generates service files, and updates
Program.cs. - An optional AI step named
AI review and cleanupreviews 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