Each module now wires itself, and the build writes the lists
The shared service list is deleted, the shared DbContext shrinks from 343 lines to 30, and nothing else changed.
One commit of 53 files: the service list is gone, the table list shrinks to 30 lines
The whole conversion is one commit on a copy of the app Measured:
| Change | Files | What it does |
|---|---|---|
| Added: the generator | 1 project, 251 lines | writes the lists on every build |
| Added: one registration file per module | 23 | each module registers its own services |
| Added: one tables file per module with tables | 21 | each module adds its own tables |
| Deleted: the shared service list | 1 (248 lines) | nobody edits it again |
| Shrunk: the shared DbContext | 343 lines to 30 | it no longer names any module |
Server.cs changes one call, and the 5 background jobs that belong to modules move into those modules.
Before: one feature is spread over three shared files
Follow one small feature, NFC tags, through the original code. Each step is a real excerpt at commit 9fc729e:
- before/App/Modules/DomainServices.cs:52-60The shared service list: one method that registers all 67 services of the app, one by one, after 51 imports.
App/Modules/DomainServices.cs:52-60csharp namespace App.Modules;public static class DomainServices{public static IServiceCollection AddDomainServices(this IServiceCollection s){// USERs.AddScoped<IUserService, UserService>() - before/App/Modules/DomainServices.cs:167-171Somewhere in the middle, the two NFC-tag services. A new feature adds its lines here.
App/Modules/DomainServices.cs:167-171csharp // NFC tagss.AddScoped<INfcTagRepository, NfcTagRepository>().AutoTrace<INfcTagRepository>();s.AddScoped<INfcTagService, NfcTagService>().AutoTrace<INfcTagService>(); - before/App/StartUp/Database/MainDbContext.cs:63-66The shared DbContext lists every table; the NFC-tag table is one line among 33.
App/StartUp/Database/MainDbContext.cs:63-66csharp // Subscription (paid tiers)public DbSet<UserSubscriptionData> UserSubscriptions { get; set; }// NFC tags (physical tag → habit mapping)public DbSet<NfcTagData> NfcTags { get; set; } - before/App/StartUp/Database/MainDbContext.cs:271-283The same file also holds every table's indexes and links, here the NFC-tag table's.
App/StartUp/Database/MainDbContext.cs:271-283csharp // NFC tags: natural key = tag id from the physical tag's URL. The cascades// cover hard deletes (user purge); habit deletion is a soft delete, so// HabitRepository.Delete releases tags explicitly.var nfcTag = modelBuilder.Entity<NfcTagData>();nfcTag.HasIndex(x => x.UserId);nfcTag.HasOne(x => x.User).WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);nfcTag.HasOne(x => x.Habit).WithMany().HasForeignKey(x => x.HabitId).OnDelete(DeleteBehavior.Cascade); - before/App/StartUp/Server.cs:153-162Start-up calls the shared list, and names each module's background job by hand.
App/StartUp/Server.cs:153-162csharp services.AddDomainServices();if (strava.CurrentValue.Enabled)services.AddScoped<Domain.Proof.IProofPlugin, Domain.Strava.StravaProofPlugin>();// Background jobsservices.AddHostedService<App.Modules.Check.CheckSchedulerHostedService>();services.AddHostedService<PenaltyProcessorHostedService>();services.AddHostedService<App.Modules.Disbursement.DisbursementHostedService>();services.AddHostedService<App.Modules.Subscription.SubscriptionRenewalHostedService>();services.AddHostedService<App.Modules.Strava.StravaWebhookHostedService>();
Three shared files, and a new feature with a table edits all three From code.
After: the feature's wiring sits in its own folder, and the build finds it
A source generator is a small C# program that runs inside the compiler on every build and writes extra C# code. That code is never saved in git. An entity configuration is a small class that describes one table's indexes and links.
The same feature after the conversion; again each step is real code:
- after/App/Modules/NfcTag/NfcTagRegistration.cs:8-20The module registers its own services. The [ServiceModule] marker is how the build finds this class.
App/Modules/NfcTag/NfcTagRegistration.cs:8-20csharp // This module's services. Found by the source generator through [ServiceModule]; no shared list names it.[ServiceModule]public static class NfcTagRegistration{public static IServiceCollection AddNfcTagModule(this IServiceCollection s){s.AddScoped<INfcTagRepository, NfcTagRepository>().AutoTrace<INfcTagRepository>();s.AddScoped<INfcTagService, NfcTagService>().AutoTrace<INfcTagService>();return s;}} - after/App/Modules/NfcTag/Data/NfcTagTables.cs:5-33The module adds its own table to the one DbContext (C# lets one class be written in several files), and its table details move here unchanged.
App/Modules/NfcTag/Data/NfcTagTables.cs:5-33csharp namespace App.StartUp.Database{public partial class MainDbContext{// NFC tags (physical tag → habit mapping)public DbSet<App.Modules.NfcTag.Data.NfcTagData> NfcTags { get; set; }}}namespace App.Modules.NfcTag.Data{// Natural key = tag id from the physical tag's URL. The cascades cover hard deletes (user purge);// habit deletion is a soft delete, so HabitRepository.Delete releases tags explicitly.public class NfcTagDataConfiguration : IEntityTypeConfiguration<NfcTagData>{public void Configure(EntityTypeBuilder<NfcTagData> nfcTag){nfcTag.HasIndex(x => x.UserId);nfcTag.HasOne(x => x.User).WithMany().HasForeignKey(x => x.UserId).OnDelete(DeleteBehavior.Cascade);nfcTag.HasOne(x => x.Habit).WithMany().HasForeignKey(x => x.HabitId).OnDelete(DeleteBehavior.Cascade);}}} - after/App/StartUp/Database/MainDbContext.cs:9-30The shared DbContext is 30 lines and names no module: it applies what the build found.
App/StartUp/Database/MainDbContext.cs:9-30csharp // The one DbContext. Its tables are NOT listed here: each module adds its own DbSet properties// with `public partial class MainDbContext` in App/Modules/<Module>/Data/<Module>Tables.cs, and// its own IEntityTypeConfiguration classes in the same file. The build collects both.public partial class MainDbContext(IOptionsMonitor<Dictionary<string, DatabaseOption>> options, ILoggerFactory factory): DbContext{public const string Key = "MAIN";protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseLoggerFactory(factory).AddPostgres(options.CurrentValue, Key).UseExceptionProcessor();}protected override void OnModelCreating(ModelBuilder modelBuilder){// Written by the source generator (App.Gen) from every IEntityTypeConfiguration<T> in App.GeneratedModel.ApplyEntityConfigurations(modelBuilder);}} - after/App/StartUp/Server.cs:153-155Start-up makes one call; only the optional Strava plug-in stays here, because it depends on a setting.
App/StartUp/Server.cs:153-155csharp services.AddServiceModules(); // generated: one call per [ServiceModule] classif (strava.CurrentValue.Enabled)services.AddScoped<Domain.Proof.IProofPlugin, Domain.Strava.StravaProofPlugin>();
It is still the one DbContext, with the same tables and names From code.
The build writes the lists as plain code, and checks the wiring
The generator's real output from the build, not saved in git:
- after/generated/GeneratedModules.g.cs:108-116One plain call per module, in dependency order: 23 modules found.
generated/GeneratedModules.g.cs:108-116csharp public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddServiceModules(this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services){global::App.Modules.System.SystemRegistration.AddSystemModule(services);global::App.Modules.Proof.ProofRegistration.AddProofModule(services);global::App.Modules.Causes.CausesRegistration.AddCausesModule(services);global::App.Modules.Charities.CharitiesRegistration.AddCharitiesModule(services);global::App.Modules.NfcTag.NfcTagRegistration.AddNfcTagModule(services);global::App.Modules.Habit.HabitRegistration.AddHabitModule(services);global::App.Modules.Users.UsersRegistration.AddUsersModule(services); - after/generated/GeneratedModel.g.cs:42-46One line per entity configuration, applied to the one DbContext: 33 found.
generated/GeneratedModel.g.cs:42-46csharp public static void ApplyEntityConfigurations(global::Microsoft.EntityFrameworkCore.ModelBuilder modelBuilder){modelBuilder.ApplyConfiguration<global::App.Modules.Causes.Data.CauseData>(new global::App.Modules.Causes.Data.CauseDataConfiguration());modelBuilder.ApplyConfiguration<global::App.Modules.Charities.Data.CharityCauseData>(new global::App.Modules.Charities.Data.CharityCauseDataConfiguration());modelBuilder.ApplyConfiguration<global::App.Modules.Charities.Data.CharityData>(new global::App.Modules.Charities.Data.CharityDataConfiguration()); - after/Gen/ModuleGenerator.cs:35-40The build also checks the wiring: a service registered twice, a missing service or a loop is a build error with file and line.
Gen/ModuleGenerator.cs:35-40csharp private static readonly DiagnosticDescriptor Duplicate = new("DIG001", "Duplicate service", "{0} is registered by more than one module: {1}", "Wiring", DiagnosticSeverity.Error, true);private static readonly DiagnosticDescriptor Missing = new("DIG002", "Missing dependency", "{0} needs {1}, but no module registers it", "Wiring", DiagnosticSeverity.Error, true);private static readonly DiagnosticDescriptor Cycle = new(
There is no search at run time: what runs is ordinary C# written at build time From code.
- Two modules may both add an
IStakeBinding, because the service that uses them takes all of them as a list. - The check covers only our own types; framework services come from Server.cs.